GNU Linux-libre 4.14.303-gnu1
[releases.git] / fs / cifs / connect.c
1 /*
2  *   fs/cifs/connect.c
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2011
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  *   This library is free software; you can redistribute it and/or modify
8  *   it under the terms of the GNU Lesser General Public License as published
9  *   by the Free Software Foundation; either version 2.1 of the License, or
10  *   (at your option) any later version.
11  *
12  *   This library is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
15  *   the GNU Lesser General Public License for more details.
16  *
17  *   You should have received a copy of the GNU Lesser General Public License
18  *   along with this library; if not, write to the Free Software
19  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  */
21 #include <linux/fs.h>
22 #include <linux/net.h>
23 #include <linux/string.h>
24 #include <linux/sched/signal.h>
25 #include <linux/list.h>
26 #include <linux/wait.h>
27 #include <linux/slab.h>
28 #include <linux/pagemap.h>
29 #include <linux/ctype.h>
30 #include <linux/utsname.h>
31 #include <linux/mempool.h>
32 #include <linux/delay.h>
33 #include <linux/completion.h>
34 #include <linux/kthread.h>
35 #include <linux/pagevec.h>
36 #include <linux/freezer.h>
37 #include <linux/namei.h>
38 #include <linux/uuid.h>
39 #include <linux/uaccess.h>
40 #include <asm/processor.h>
41 #include <linux/inet.h>
42 #include <linux/module.h>
43 #include <keys/user-type.h>
44 #include <net/ipv6.h>
45 #include <linux/parser.h>
46 #include <linux/bvec.h>
47
48 #include "cifspdu.h"
49 #include "cifsglob.h"
50 #include "cifsproto.h"
51 #include "cifs_unicode.h"
52 #include "cifs_debug.h"
53 #include "cifs_fs_sb.h"
54 #include "dns_resolve.h"
55 #include "ntlmssp.h"
56 #include "nterr.h"
57 #include "rfc1002pdu.h"
58 #include "fscache.h"
59 #include "smb2proto.h"
60
61 #define CIFS_PORT 445
62 #define RFC1001_PORT 139
63
64 extern mempool_t *cifs_req_poolp;
65
66 /* FIXME: should these be tunable? */
67 #define TLINK_ERROR_EXPIRE      (1 * HZ)
68 #define TLINK_IDLE_EXPIRE       (600 * HZ)
69
70 enum {
71         /* Mount options that take no arguments */
72         Opt_user_xattr, Opt_nouser_xattr,
73         Opt_forceuid, Opt_noforceuid,
74         Opt_forcegid, Opt_noforcegid,
75         Opt_noblocksend, Opt_noautotune,
76         Opt_hard, Opt_soft, Opt_perm, Opt_noperm,
77         Opt_mapposix, Opt_nomapposix,
78         Opt_mapchars, Opt_nomapchars, Opt_sfu,
79         Opt_nosfu, Opt_nodfs, Opt_posixpaths,
80         Opt_noposixpaths, Opt_nounix,
81         Opt_nocase,
82         Opt_brl, Opt_nobrl,
83         Opt_forcemandatorylock, Opt_setuidfromacl, Opt_setuids,
84         Opt_nosetuids, Opt_dynperm, Opt_nodynperm,
85         Opt_nohard, Opt_nosoft,
86         Opt_nointr, Opt_intr,
87         Opt_nostrictsync, Opt_strictsync,
88         Opt_serverino, Opt_noserverino,
89         Opt_rwpidforward, Opt_cifsacl, Opt_nocifsacl,
90         Opt_acl, Opt_noacl, Opt_locallease,
91         Opt_sign, Opt_seal, Opt_noac,
92         Opt_fsc, Opt_mfsymlinks,
93         Opt_multiuser, Opt_sloppy, Opt_nosharesock,
94         Opt_persistent, Opt_nopersistent,
95         Opt_resilient, Opt_noresilient,
96         Opt_domainauto,
97
98         /* Mount options which take numeric value */
99         Opt_backupuid, Opt_backupgid, Opt_uid,
100         Opt_cruid, Opt_gid, Opt_file_mode,
101         Opt_dirmode, Opt_port,
102         Opt_rsize, Opt_wsize, Opt_actimeo,
103         Opt_echo_interval, Opt_max_credits,
104         Opt_snapshot,
105
106         /* Mount options which take string value */
107         Opt_user, Opt_pass, Opt_ip,
108         Opt_domain, Opt_srcaddr, Opt_iocharset,
109         Opt_netbiosname, Opt_servern,
110         Opt_ver, Opt_vers, Opt_sec, Opt_cache,
111
112         /* Mount options to be ignored */
113         Opt_ignore,
114
115         /* Options which could be blank */
116         Opt_blank_pass,
117         Opt_blank_user,
118         Opt_blank_ip,
119
120         Opt_err
121 };
122
123 static const match_table_t cifs_mount_option_tokens = {
124
125         { Opt_user_xattr, "user_xattr" },
126         { Opt_nouser_xattr, "nouser_xattr" },
127         { Opt_forceuid, "forceuid" },
128         { Opt_noforceuid, "noforceuid" },
129         { Opt_forcegid, "forcegid" },
130         { Opt_noforcegid, "noforcegid" },
131         { Opt_noblocksend, "noblocksend" },
132         { Opt_noautotune, "noautotune" },
133         { Opt_hard, "hard" },
134         { Opt_soft, "soft" },
135         { Opt_perm, "perm" },
136         { Opt_noperm, "noperm" },
137         { Opt_mapchars, "mapchars" }, /* SFU style */
138         { Opt_nomapchars, "nomapchars" },
139         { Opt_mapposix, "mapposix" }, /* SFM style */
140         { Opt_nomapposix, "nomapposix" },
141         { Opt_sfu, "sfu" },
142         { Opt_nosfu, "nosfu" },
143         { Opt_nodfs, "nodfs" },
144         { Opt_posixpaths, "posixpaths" },
145         { Opt_noposixpaths, "noposixpaths" },
146         { Opt_nounix, "nounix" },
147         { Opt_nounix, "nolinux" },
148         { Opt_nocase, "nocase" },
149         { Opt_nocase, "ignorecase" },
150         { Opt_brl, "brl" },
151         { Opt_nobrl, "nobrl" },
152         { Opt_nobrl, "nolock" },
153         { Opt_forcemandatorylock, "forcemandatorylock" },
154         { Opt_forcemandatorylock, "forcemand" },
155         { Opt_setuids, "setuids" },
156         { Opt_nosetuids, "nosetuids" },
157         { Opt_setuidfromacl, "idsfromsid" },
158         { Opt_dynperm, "dynperm" },
159         { Opt_nodynperm, "nodynperm" },
160         { Opt_nohard, "nohard" },
161         { Opt_nosoft, "nosoft" },
162         { Opt_nointr, "nointr" },
163         { Opt_intr, "intr" },
164         { Opt_nostrictsync, "nostrictsync" },
165         { Opt_strictsync, "strictsync" },
166         { Opt_serverino, "serverino" },
167         { Opt_noserverino, "noserverino" },
168         { Opt_rwpidforward, "rwpidforward" },
169         { Opt_cifsacl, "cifsacl" },
170         { Opt_nocifsacl, "nocifsacl" },
171         { Opt_acl, "acl" },
172         { Opt_noacl, "noacl" },
173         { Opt_locallease, "locallease" },
174         { Opt_sign, "sign" },
175         { Opt_seal, "seal" },
176         { Opt_noac, "noac" },
177         { Opt_fsc, "fsc" },
178         { Opt_mfsymlinks, "mfsymlinks" },
179         { Opt_multiuser, "multiuser" },
180         { Opt_sloppy, "sloppy" },
181         { Opt_nosharesock, "nosharesock" },
182         { Opt_persistent, "persistenthandles"},
183         { Opt_nopersistent, "nopersistenthandles"},
184         { Opt_resilient, "resilienthandles"},
185         { Opt_noresilient, "noresilienthandles"},
186         { Opt_domainauto, "domainauto"},
187
188         { Opt_backupuid, "backupuid=%s" },
189         { Opt_backupgid, "backupgid=%s" },
190         { Opt_uid, "uid=%s" },
191         { Opt_cruid, "cruid=%s" },
192         { Opt_gid, "gid=%s" },
193         { Opt_file_mode, "file_mode=%s" },
194         { Opt_dirmode, "dirmode=%s" },
195         { Opt_dirmode, "dir_mode=%s" },
196         { Opt_port, "port=%s" },
197         { Opt_rsize, "rsize=%s" },
198         { Opt_wsize, "wsize=%s" },
199         { Opt_actimeo, "actimeo=%s" },
200         { Opt_echo_interval, "echo_interval=%s" },
201         { Opt_max_credits, "max_credits=%s" },
202         { Opt_snapshot, "snapshot=%s" },
203
204         { Opt_blank_user, "user=" },
205         { Opt_blank_user, "username=" },
206         { Opt_user, "user=%s" },
207         { Opt_user, "username=%s" },
208         { Opt_blank_pass, "pass=" },
209         { Opt_blank_pass, "password=" },
210         { Opt_pass, "pass=%s" },
211         { Opt_pass, "password=%s" },
212         { Opt_blank_ip, "ip=" },
213         { Opt_blank_ip, "addr=" },
214         { Opt_ip, "ip=%s" },
215         { Opt_ip, "addr=%s" },
216         { Opt_ignore, "unc=%s" },
217         { Opt_ignore, "target=%s" },
218         { Opt_ignore, "path=%s" },
219         { Opt_domain, "dom=%s" },
220         { Opt_domain, "domain=%s" },
221         { Opt_domain, "workgroup=%s" },
222         { Opt_srcaddr, "srcaddr=%s" },
223         { Opt_ignore, "prefixpath=%s" },
224         { Opt_iocharset, "iocharset=%s" },
225         { Opt_netbiosname, "netbiosname=%s" },
226         { Opt_servern, "servern=%s" },
227         { Opt_ver, "ver=%s" },
228         { Opt_vers, "vers=%s" },
229         { Opt_sec, "sec=%s" },
230         { Opt_cache, "cache=%s" },
231
232         { Opt_ignore, "cred" },
233         { Opt_ignore, "credentials" },
234         { Opt_ignore, "cred=%s" },
235         { Opt_ignore, "credentials=%s" },
236         { Opt_ignore, "guest" },
237         { Opt_ignore, "rw" },
238         { Opt_ignore, "ro" },
239         { Opt_ignore, "suid" },
240         { Opt_ignore, "nosuid" },
241         { Opt_ignore, "exec" },
242         { Opt_ignore, "noexec" },
243         { Opt_ignore, "nodev" },
244         { Opt_ignore, "noauto" },
245         { Opt_ignore, "dev" },
246         { Opt_ignore, "mand" },
247         { Opt_ignore, "nomand" },
248         { Opt_ignore, "_netdev" },
249
250         { Opt_err, NULL }
251 };
252
253 enum {
254         Opt_sec_krb5, Opt_sec_krb5i, Opt_sec_krb5p,
255         Opt_sec_ntlmsspi, Opt_sec_ntlmssp,
256         Opt_ntlm, Opt_sec_ntlmi, Opt_sec_ntlmv2,
257         Opt_sec_ntlmv2i, Opt_sec_lanman,
258         Opt_sec_none,
259
260         Opt_sec_err
261 };
262
263 static const match_table_t cifs_secflavor_tokens = {
264         { Opt_sec_krb5, "krb5" },
265         { Opt_sec_krb5i, "krb5i" },
266         { Opt_sec_krb5p, "krb5p" },
267         { Opt_sec_ntlmsspi, "ntlmsspi" },
268         { Opt_sec_ntlmssp, "ntlmssp" },
269         { Opt_ntlm, "ntlm" },
270         { Opt_sec_ntlmi, "ntlmi" },
271         { Opt_sec_ntlmv2, "nontlm" },
272         { Opt_sec_ntlmv2, "ntlmv2" },
273         { Opt_sec_ntlmv2i, "ntlmv2i" },
274         { Opt_sec_lanman, "lanman" },
275         { Opt_sec_none, "none" },
276
277         { Opt_sec_err, NULL }
278 };
279
280 /* cache flavors */
281 enum {
282         Opt_cache_loose,
283         Opt_cache_strict,
284         Opt_cache_none,
285         Opt_cache_err
286 };
287
288 static const match_table_t cifs_cacheflavor_tokens = {
289         { Opt_cache_loose, "loose" },
290         { Opt_cache_strict, "strict" },
291         { Opt_cache_none, "none" },
292         { Opt_cache_err, NULL }
293 };
294
295 static const match_table_t cifs_smb_version_tokens = {
296         { Smb_1, SMB1_VERSION_STRING },
297         { Smb_20, SMB20_VERSION_STRING},
298         { Smb_21, SMB21_VERSION_STRING },
299         { Smb_30, SMB30_VERSION_STRING },
300         { Smb_302, SMB302_VERSION_STRING },
301 #ifdef CONFIG_CIFS_SMB311
302         { Smb_311, SMB311_VERSION_STRING },
303         { Smb_311, ALT_SMB311_VERSION_STRING },
304 #endif /* SMB311 */
305         { Smb_3any, SMB3ANY_VERSION_STRING },
306         { Smb_default, SMBDEFAULT_VERSION_STRING },
307         { Smb_version_err, NULL }
308 };
309
310 static int ip_connect(struct TCP_Server_Info *server);
311 static int generic_ip_connect(struct TCP_Server_Info *server);
312 static void tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink);
313 static void cifs_prune_tlinks(struct work_struct *work);
314 static int cifs_setup_volume_info(struct smb_vol *volume_info, char *mount_data,
315                                         const char *devname);
316
317 /*
318  * Resolve hostname and set ip addr in tcp ses. Useful for hostnames that may
319  * get their ip addresses changed at some point.
320  *
321  * This should be called with server->srv_mutex held.
322  */
323 #ifdef CONFIG_CIFS_DFS_UPCALL
324 static int reconn_set_ipaddr(struct TCP_Server_Info *server)
325 {
326         int rc;
327         int len;
328         char *unc, *ipaddr = NULL;
329
330         if (!server->hostname)
331                 return -EINVAL;
332
333         len = strlen(server->hostname) + 3;
334
335         unc = kmalloc(len, GFP_KERNEL);
336         if (!unc) {
337                 cifs_dbg(FYI, "%s: failed to create UNC path\n", __func__);
338                 return -ENOMEM;
339         }
340         snprintf(unc, len, "\\\\%s", server->hostname);
341
342         rc = dns_resolve_server_name_to_ip(unc, &ipaddr);
343         kfree(unc);
344
345         if (rc < 0) {
346                 cifs_dbg(FYI, "%s: failed to resolve server part of %s to IP: %d\n",
347                          __func__, server->hostname, rc);
348                 return rc;
349         }
350
351         spin_lock(&cifs_tcp_ses_lock);
352         rc = cifs_convert_address((struct sockaddr *)&server->dstaddr, ipaddr,
353                                   strlen(ipaddr));
354         spin_unlock(&cifs_tcp_ses_lock);
355         kfree(ipaddr);
356
357         return !rc ? -1 : 0;
358 }
359 #else
360 static inline int reconn_set_ipaddr(struct TCP_Server_Info *server)
361 {
362         return 0;
363 }
364 #endif
365
366 /*
367  * cifs tcp session reconnection
368  *
369  * mark tcp session as reconnecting so temporarily locked
370  * mark all smb sessions as reconnecting for tcp session
371  * reconnect tcp session
372  * wake up waiters on reconnection? - (not needed currently)
373  */
374 int
375 cifs_reconnect(struct TCP_Server_Info *server)
376 {
377         int rc = 0;
378         struct list_head *tmp, *tmp2;
379         struct cifs_ses *ses;
380         struct cifs_tcon *tcon;
381         struct mid_q_entry *mid_entry;
382         struct list_head retry_list;
383
384         spin_lock(&GlobalMid_Lock);
385         if (server->tcpStatus == CifsExiting) {
386                 /* the demux thread will exit normally
387                 next time through the loop */
388                 spin_unlock(&GlobalMid_Lock);
389                 return rc;
390         } else
391                 server->tcpStatus = CifsNeedReconnect;
392         spin_unlock(&GlobalMid_Lock);
393         server->maxBuf = 0;
394         server->max_read = 0;
395
396         cifs_dbg(FYI, "Reconnecting tcp session\n");
397
398         /* before reconnecting the tcp session, mark the smb session (uid)
399                 and the tid bad so they are not used until reconnected */
400         cifs_dbg(FYI, "%s: marking sessions and tcons for reconnect\n",
401                  __func__);
402         spin_lock(&cifs_tcp_ses_lock);
403         list_for_each(tmp, &server->smb_ses_list) {
404                 ses = list_entry(tmp, struct cifs_ses, smb_ses_list);
405                 ses->need_reconnect = true;
406                 ses->ipc_tid = 0;
407                 list_for_each(tmp2, &ses->tcon_list) {
408                         tcon = list_entry(tmp2, struct cifs_tcon, tcon_list);
409                         tcon->need_reconnect = true;
410                 }
411         }
412         spin_unlock(&cifs_tcp_ses_lock);
413
414         /* do not want to be sending data on a socket we are freeing */
415         cifs_dbg(FYI, "%s: tearing down socket\n", __func__);
416         mutex_lock(&server->srv_mutex);
417         if (server->ssocket) {
418                 cifs_dbg(FYI, "State: 0x%x Flags: 0x%lx\n",
419                          server->ssocket->state, server->ssocket->flags);
420                 kernel_sock_shutdown(server->ssocket, SHUT_WR);
421                 cifs_dbg(FYI, "Post shutdown state: 0x%x Flags: 0x%lx\n",
422                          server->ssocket->state, server->ssocket->flags);
423                 sock_release(server->ssocket);
424                 server->ssocket = NULL;
425         }
426         server->sequence_number = 0;
427         server->session_estab = false;
428         kfree(server->session_key.response);
429         server->session_key.response = NULL;
430         server->session_key.len = 0;
431         server->lstrp = jiffies;
432
433         /* mark submitted MIDs for retry and issue callback */
434         INIT_LIST_HEAD(&retry_list);
435         cifs_dbg(FYI, "%s: moving mids to private list\n", __func__);
436         spin_lock(&GlobalMid_Lock);
437         list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
438                 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
439                 if (mid_entry->mid_state == MID_REQUEST_SUBMITTED)
440                         mid_entry->mid_state = MID_RETRY_NEEDED;
441                 list_move(&mid_entry->qhead, &retry_list);
442         }
443         spin_unlock(&GlobalMid_Lock);
444         mutex_unlock(&server->srv_mutex);
445
446         cifs_dbg(FYI, "%s: issuing mid callbacks\n", __func__);
447         list_for_each_safe(tmp, tmp2, &retry_list) {
448                 mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
449                 list_del_init(&mid_entry->qhead);
450                 mid_entry->callback(mid_entry);
451         }
452
453         do {
454                 try_to_freeze();
455
456                 /* we should try only the port we connected to before */
457                 mutex_lock(&server->srv_mutex);
458                 rc = generic_ip_connect(server);
459                 if (rc) {
460                         cifs_dbg(FYI, "reconnect error %d\n", rc);
461                         rc = reconn_set_ipaddr(server);
462                         if (rc) {
463                                 cifs_dbg(FYI, "%s: failed to resolve hostname: %d\n",
464                                          __func__, rc);
465                         }
466                         mutex_unlock(&server->srv_mutex);
467                         msleep(3000);
468                 } else {
469                         atomic_inc(&tcpSesReconnectCount);
470                         spin_lock(&GlobalMid_Lock);
471                         if (server->tcpStatus != CifsExiting)
472                                 server->tcpStatus = CifsNeedNegotiate;
473                         spin_unlock(&GlobalMid_Lock);
474                         mutex_unlock(&server->srv_mutex);
475                 }
476         } while (server->tcpStatus == CifsNeedReconnect);
477
478         if (server->tcpStatus == CifsNeedNegotiate)
479                 mod_delayed_work(cifsiod_wq, &server->echo, 0);
480
481         return rc;
482 }
483
484 static void
485 cifs_echo_request(struct work_struct *work)
486 {
487         int rc;
488         struct TCP_Server_Info *server = container_of(work,
489                                         struct TCP_Server_Info, echo.work);
490         unsigned long echo_interval;
491
492         /*
493          * If we need to renegotiate, set echo interval to zero to
494          * immediately call echo service where we can renegotiate.
495          */
496         if (server->tcpStatus == CifsNeedNegotiate)
497                 echo_interval = 0;
498         else
499                 echo_interval = server->echo_interval;
500
501         /*
502          * We cannot send an echo if it is disabled.
503          * Also, no need to ping if we got a response recently.
504          */
505
506         if (server->tcpStatus == CifsNeedReconnect ||
507             server->tcpStatus == CifsExiting ||
508             server->tcpStatus == CifsNew ||
509             (server->ops->can_echo && !server->ops->can_echo(server)) ||
510             time_before(jiffies, server->lstrp + echo_interval - HZ))
511                 goto requeue_echo;
512
513         rc = server->ops->echo ? server->ops->echo(server) : -ENOSYS;
514         if (rc)
515                 cifs_dbg(FYI, "Unable to send echo request to server: %s\n",
516                          server->hostname);
517
518 requeue_echo:
519         queue_delayed_work(cifsiod_wq, &server->echo, server->echo_interval);
520 }
521
522 static bool
523 allocate_buffers(struct TCP_Server_Info *server)
524 {
525         if (!server->bigbuf) {
526                 server->bigbuf = (char *)cifs_buf_get();
527                 if (!server->bigbuf) {
528                         cifs_dbg(VFS, "No memory for large SMB response\n");
529                         msleep(3000);
530                         /* retry will check if exiting */
531                         return false;
532                 }
533         } else if (server->large_buf) {
534                 /* we are reusing a dirty large buf, clear its start */
535                 memset(server->bigbuf, 0, HEADER_SIZE(server));
536         }
537
538         if (!server->smallbuf) {
539                 server->smallbuf = (char *)cifs_small_buf_get();
540                 if (!server->smallbuf) {
541                         cifs_dbg(VFS, "No memory for SMB response\n");
542                         msleep(1000);
543                         /* retry will check if exiting */
544                         return false;
545                 }
546                 /* beginning of smb buffer is cleared in our buf_get */
547         } else {
548                 /* if existing small buf clear beginning */
549                 memset(server->smallbuf, 0, HEADER_SIZE(server));
550         }
551
552         return true;
553 }
554
555 static bool
556 server_unresponsive(struct TCP_Server_Info *server)
557 {
558         /*
559          * We need to wait 3 echo intervals to make sure we handle such
560          * situations right:
561          * 1s  client sends a normal SMB request
562          * 3s  client gets a response
563          * 30s echo workqueue job pops, and decides we got a response recently
564          *     and don't need to send another
565          * ...
566          * 65s kernel_recvmsg times out, and we see that we haven't gotten
567          *     a response in >60s.
568          */
569         if ((server->tcpStatus == CifsGood ||
570             server->tcpStatus == CifsNeedNegotiate) &&
571             time_after(jiffies, server->lstrp + 3 * server->echo_interval)) {
572                 cifs_dbg(VFS, "Server %s has not responded in %lu seconds. Reconnecting...\n",
573                          server->hostname, (3 * server->echo_interval) / HZ);
574                 cifs_reconnect(server);
575                 wake_up(&server->response_q);
576                 return true;
577         }
578
579         return false;
580 }
581
582 static inline bool
583 zero_credits(struct TCP_Server_Info *server)
584 {
585         int val;
586
587         spin_lock(&server->req_lock);
588         val = server->credits + server->echo_credits + server->oplock_credits;
589         if (server->in_flight == 0 && val == 0) {
590                 spin_unlock(&server->req_lock);
591                 return true;
592         }
593         spin_unlock(&server->req_lock);
594         return false;
595 }
596
597 static int
598 cifs_readv_from_socket(struct TCP_Server_Info *server, struct msghdr *smb_msg)
599 {
600         int length = 0;
601         int total_read;
602
603         smb_msg->msg_control = NULL;
604         smb_msg->msg_controllen = 0;
605
606         for (total_read = 0; msg_data_left(smb_msg); total_read += length) {
607                 try_to_freeze();
608
609                 /* reconnect if no credits and no requests in flight */
610                 if (zero_credits(server)) {
611                         cifs_reconnect(server);
612                         return -ECONNABORTED;
613                 }
614
615                 if (server_unresponsive(server))
616                         return -ECONNABORTED;
617
618                 length = sock_recvmsg(server->ssocket, smb_msg, 0);
619
620                 if (server->tcpStatus == CifsExiting)
621                         return -ESHUTDOWN;
622
623                 if (server->tcpStatus == CifsNeedReconnect) {
624                         cifs_reconnect(server);
625                         return -ECONNABORTED;
626                 }
627
628                 if (length == -ERESTARTSYS ||
629                     length == -EAGAIN ||
630                     length == -EINTR) {
631                         /*
632                          * Minimum sleep to prevent looping, allowing socket
633                          * to clear and app threads to set tcpStatus
634                          * CifsNeedReconnect if server hung.
635                          */
636                         usleep_range(1000, 2000);
637                         length = 0;
638                         continue;
639                 }
640
641                 if (length <= 0) {
642                         cifs_dbg(FYI, "Received no data or error: %d\n", length);
643                         cifs_reconnect(server);
644                         return -ECONNABORTED;
645                 }
646         }
647         return total_read;
648 }
649
650 int
651 cifs_read_from_socket(struct TCP_Server_Info *server, char *buf,
652                       unsigned int to_read)
653 {
654         struct msghdr smb_msg;
655         struct kvec iov = {.iov_base = buf, .iov_len = to_read};
656         iov_iter_kvec(&smb_msg.msg_iter, READ | ITER_KVEC, &iov, 1, to_read);
657
658         return cifs_readv_from_socket(server, &smb_msg);
659 }
660
661 int
662 cifs_read_page_from_socket(struct TCP_Server_Info *server, struct page *page,
663                       unsigned int to_read)
664 {
665         struct msghdr smb_msg;
666         struct bio_vec bv = {.bv_page = page, .bv_len = to_read};
667         iov_iter_bvec(&smb_msg.msg_iter, READ | ITER_BVEC, &bv, 1, to_read);
668         return cifs_readv_from_socket(server, &smb_msg);
669 }
670
671 static bool
672 is_smb_response(struct TCP_Server_Info *server, unsigned char type)
673 {
674         /*
675          * The first byte big endian of the length field,
676          * is actually not part of the length but the type
677          * with the most common, zero, as regular data.
678          */
679         switch (type) {
680         case RFC1002_SESSION_MESSAGE:
681                 /* Regular SMB response */
682                 return true;
683         case RFC1002_SESSION_KEEP_ALIVE:
684                 cifs_dbg(FYI, "RFC 1002 session keep alive\n");
685                 break;
686         case RFC1002_POSITIVE_SESSION_RESPONSE:
687                 cifs_dbg(FYI, "RFC 1002 positive session response\n");
688                 break;
689         case RFC1002_NEGATIVE_SESSION_RESPONSE:
690                 /*
691                  * We get this from Windows 98 instead of an error on
692                  * SMB negprot response.
693                  */
694                 cifs_dbg(FYI, "RFC 1002 negative session response\n");
695                 /* give server a second to clean up */
696                 msleep(1000);
697                 /*
698                  * Always try 445 first on reconnect since we get NACK
699                  * on some if we ever connected to port 139 (the NACK
700                  * is since we do not begin with RFC1001 session
701                  * initialize frame).
702                  */
703                 cifs_set_port((struct sockaddr *)&server->dstaddr, CIFS_PORT);
704                 cifs_reconnect(server);
705                 wake_up(&server->response_q);
706                 break;
707         default:
708                 cifs_dbg(VFS, "RFC 1002 unknown response type 0x%x\n", type);
709                 cifs_reconnect(server);
710         }
711
712         return false;
713 }
714
715 void
716 dequeue_mid(struct mid_q_entry *mid, bool malformed)
717 {
718 #ifdef CONFIG_CIFS_STATS2
719         mid->when_received = jiffies;
720 #endif
721         spin_lock(&GlobalMid_Lock);
722         if (!malformed)
723                 mid->mid_state = MID_RESPONSE_RECEIVED;
724         else
725                 mid->mid_state = MID_RESPONSE_MALFORMED;
726         list_del_init(&mid->qhead);
727         spin_unlock(&GlobalMid_Lock);
728 }
729
730 static void
731 handle_mid(struct mid_q_entry *mid, struct TCP_Server_Info *server,
732            char *buf, int malformed)
733 {
734         if (server->ops->check_trans2 &&
735             server->ops->check_trans2(mid, server, buf, malformed))
736                 return;
737         mid->resp_buf = buf;
738         mid->large_buf = server->large_buf;
739         /* Was previous buf put in mpx struct for multi-rsp? */
740         if (!mid->multiRsp) {
741                 /* smb buffer will be freed by user thread */
742                 if (server->large_buf)
743                         server->bigbuf = NULL;
744                 else
745                         server->smallbuf = NULL;
746         }
747         dequeue_mid(mid, malformed);
748 }
749
750 static void clean_demultiplex_info(struct TCP_Server_Info *server)
751 {
752         int length;
753
754         /* take it off the list, if it's not already */
755         spin_lock(&cifs_tcp_ses_lock);
756         list_del_init(&server->tcp_ses_list);
757         spin_unlock(&cifs_tcp_ses_lock);
758
759         cancel_delayed_work_sync(&server->echo);
760
761         spin_lock(&GlobalMid_Lock);
762         server->tcpStatus = CifsExiting;
763         spin_unlock(&GlobalMid_Lock);
764         wake_up_all(&server->response_q);
765
766         /* check if we have blocked requests that need to free */
767         spin_lock(&server->req_lock);
768         if (server->credits <= 0)
769                 server->credits = 1;
770         spin_unlock(&server->req_lock);
771         /*
772          * Although there should not be any requests blocked on this queue it
773          * can not hurt to be paranoid and try to wake up requests that may
774          * haven been blocked when more than 50 at time were on the wire to the
775          * same server - they now will see the session is in exit state and get
776          * out of SendReceive.
777          */
778         wake_up_all(&server->request_q);
779         /* give those requests time to exit */
780         msleep(125);
781
782         if (server->ssocket) {
783                 sock_release(server->ssocket);
784                 server->ssocket = NULL;
785         }
786
787         if (!list_empty(&server->pending_mid_q)) {
788                 struct list_head dispose_list;
789                 struct mid_q_entry *mid_entry;
790                 struct list_head *tmp, *tmp2;
791
792                 INIT_LIST_HEAD(&dispose_list);
793                 spin_lock(&GlobalMid_Lock);
794                 list_for_each_safe(tmp, tmp2, &server->pending_mid_q) {
795                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
796                         cifs_dbg(FYI, "Clearing mid 0x%llx\n", mid_entry->mid);
797                         mid_entry->mid_state = MID_SHUTDOWN;
798                         list_move(&mid_entry->qhead, &dispose_list);
799                 }
800                 spin_unlock(&GlobalMid_Lock);
801
802                 /* now walk dispose list and issue callbacks */
803                 list_for_each_safe(tmp, tmp2, &dispose_list) {
804                         mid_entry = list_entry(tmp, struct mid_q_entry, qhead);
805                         cifs_dbg(FYI, "Callback mid 0x%llx\n", mid_entry->mid);
806                         list_del_init(&mid_entry->qhead);
807                         mid_entry->callback(mid_entry);
808                 }
809                 /* 1/8th of sec is more than enough time for them to exit */
810                 msleep(125);
811         }
812
813         if (!list_empty(&server->pending_mid_q)) {
814                 /*
815                  * mpx threads have not exited yet give them at least the smb
816                  * send timeout time for long ops.
817                  *
818                  * Due to delays on oplock break requests, we need to wait at
819                  * least 45 seconds before giving up on a request getting a
820                  * response and going ahead and killing cifsd.
821                  */
822                 cifs_dbg(FYI, "Wait for exit from demultiplex thread\n");
823                 msleep(46000);
824                 /*
825                  * If threads still have not exited they are probably never
826                  * coming home not much else we can do but free the memory.
827                  */
828         }
829
830         kfree(server->hostname);
831         kfree(server);
832
833         length = atomic_dec_return(&tcpSesAllocCount);
834         if (length > 0)
835                 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
836 }
837
838 static int
839 standard_receive3(struct TCP_Server_Info *server, struct mid_q_entry *mid)
840 {
841         int length;
842         char *buf = server->smallbuf;
843         unsigned int pdu_length = get_rfc1002_length(buf);
844
845         /* make sure this will fit in a large buffer */
846         if (pdu_length > CIFSMaxBufSize + MAX_HEADER_SIZE(server) - 4) {
847                 cifs_dbg(VFS, "SMB response too long (%u bytes)\n", pdu_length);
848                 cifs_reconnect(server);
849                 wake_up(&server->response_q);
850                 return -ECONNABORTED;
851         }
852
853         /* switch to large buffer if too big for a small one */
854         if (pdu_length > MAX_CIFS_SMALL_BUFFER_SIZE - 4) {
855                 server->large_buf = true;
856                 memcpy(server->bigbuf, buf, server->total_read);
857                 buf = server->bigbuf;
858         }
859
860         /* now read the rest */
861         length = cifs_read_from_socket(server, buf + HEADER_SIZE(server) - 1,
862                                 pdu_length - HEADER_SIZE(server) + 1 + 4);
863         if (length < 0)
864                 return length;
865         server->total_read += length;
866
867         dump_smb(buf, server->total_read);
868
869         return cifs_handle_standard(server, mid);
870 }
871
872 int
873 cifs_handle_standard(struct TCP_Server_Info *server, struct mid_q_entry *mid)
874 {
875         char *buf = server->large_buf ? server->bigbuf : server->smallbuf;
876         int length;
877
878         /*
879          * We know that we received enough to get to the MID as we
880          * checked the pdu_length earlier. Now check to see
881          * if the rest of the header is OK. We borrow the length
882          * var for the rest of the loop to avoid a new stack var.
883          *
884          * 48 bytes is enough to display the header and a little bit
885          * into the payload for debugging purposes.
886          */
887         length = server->ops->check_message(buf, server->total_read, server);
888         if (length != 0)
889                 cifs_dump_mem("Bad SMB: ", buf,
890                         min_t(unsigned int, server->total_read, 48));
891
892         if (server->ops->is_session_expired &&
893             server->ops->is_session_expired(buf)) {
894                 cifs_reconnect(server);
895                 wake_up(&server->response_q);
896                 return -1;
897         }
898
899         if (server->ops->is_status_pending &&
900             server->ops->is_status_pending(buf, server, length))
901                 return -1;
902
903         if (!mid)
904                 return length;
905
906         handle_mid(mid, server, buf, length);
907         return 0;
908 }
909
910 static int
911 cifs_demultiplex_thread(void *p)
912 {
913         int length;
914         struct TCP_Server_Info *server = p;
915         unsigned int pdu_length;
916         char *buf = NULL;
917         struct task_struct *task_to_wake = NULL;
918         struct mid_q_entry *mid_entry;
919
920         current->flags |= PF_MEMALLOC;
921         cifs_dbg(FYI, "Demultiplex PID: %d\n", task_pid_nr(current));
922
923         length = atomic_inc_return(&tcpSesAllocCount);
924         if (length > 1)
925                 mempool_resize(cifs_req_poolp, length + cifs_min_rcv);
926
927         set_freezable();
928         allow_kernel_signal(SIGKILL);
929         while (server->tcpStatus != CifsExiting) {
930                 if (try_to_freeze())
931                         continue;
932
933                 if (!allocate_buffers(server))
934                         continue;
935
936                 server->large_buf = false;
937                 buf = server->smallbuf;
938                 pdu_length = 4; /* enough to get RFC1001 header */
939
940                 length = cifs_read_from_socket(server, buf, pdu_length);
941                 if (length < 0)
942                         continue;
943                 server->total_read = length;
944
945                 /*
946                  * The right amount was read from socket - 4 bytes,
947                  * so we can now interpret the length field.
948                  */
949                 pdu_length = get_rfc1002_length(buf);
950
951                 cifs_dbg(FYI, "RFC1002 header 0x%x\n", pdu_length);
952                 if (!is_smb_response(server, buf[0]))
953                         continue;
954
955                 /* make sure we have enough to get to the MID */
956                 if (pdu_length < HEADER_SIZE(server) - 1 - 4) {
957                         cifs_dbg(VFS, "SMB response too short (%u bytes)\n",
958                                  pdu_length);
959                         cifs_reconnect(server);
960                         wake_up(&server->response_q);
961                         continue;
962                 }
963
964                 /* read down to the MID */
965                 length = cifs_read_from_socket(server, buf + 4,
966                                                HEADER_SIZE(server) - 1 - 4);
967                 if (length < 0)
968                         continue;
969                 server->total_read += length;
970
971                 mid_entry = NULL;
972                 if (server->ops->is_transform_hdr &&
973                     server->ops->receive_transform &&
974                     server->ops->is_transform_hdr(buf)) {
975                         length = server->ops->receive_transform(server,
976                                                                 &mid_entry);
977                 } else {
978                         mid_entry = server->ops->find_mid(server, buf);
979
980                         if (!mid_entry || !mid_entry->receive)
981                                 length = standard_receive3(server, mid_entry);
982                         else
983                                 length = mid_entry->receive(server, mid_entry);
984                 }
985
986                 if (length < 0) {
987                         if (mid_entry)
988                                 cifs_mid_q_entry_release(mid_entry);
989                         continue;
990                 }
991
992                 if (server->large_buf)
993                         buf = server->bigbuf;
994
995                 server->lstrp = jiffies;
996                 if (mid_entry != NULL) {
997                         if ((mid_entry->mid_flags & MID_WAIT_CANCELLED) &&
998                              mid_entry->mid_state == MID_RESPONSE_RECEIVED &&
999                                         server->ops->handle_cancelled_mid)
1000                                 server->ops->handle_cancelled_mid(
1001                                                         mid_entry->resp_buf,
1002                                                         server);
1003
1004                         if (!mid_entry->multiRsp || mid_entry->multiEnd)
1005                                 mid_entry->callback(mid_entry);
1006
1007                         cifs_mid_q_entry_release(mid_entry);
1008                 } else if (server->ops->is_oplock_break &&
1009                            server->ops->is_oplock_break(buf, server)) {
1010                         cifs_dbg(FYI, "Received oplock break\n");
1011                 } else {
1012                         cifs_dbg(VFS, "No task to wake, unknown frame received! NumMids %d\n",
1013                                  atomic_read(&midCount));
1014                         cifs_dump_mem("Received Data is: ", buf,
1015                                       HEADER_SIZE(server));
1016 #ifdef CONFIG_CIFS_DEBUG2
1017                         if (server->ops->dump_detail)
1018                                 server->ops->dump_detail(buf);
1019                         cifs_dump_mids(server);
1020 #endif /* CIFS_DEBUG2 */
1021
1022                 }
1023         } /* end while !EXITING */
1024
1025         /* buffer usually freed in free_mid - need to free it here on exit */
1026         cifs_buf_release(server->bigbuf);
1027         if (server->smallbuf) /* no sense logging a debug message if NULL */
1028                 cifs_small_buf_release(server->smallbuf);
1029
1030         task_to_wake = xchg(&server->tsk, NULL);
1031         clean_demultiplex_info(server);
1032
1033         /* if server->tsk was NULL then wait for a signal before exiting */
1034         if (!task_to_wake) {
1035                 set_current_state(TASK_INTERRUPTIBLE);
1036                 while (!signal_pending(current)) {
1037                         schedule();
1038                         set_current_state(TASK_INTERRUPTIBLE);
1039                 }
1040                 set_current_state(TASK_RUNNING);
1041         }
1042
1043         module_put_and_exit(0);
1044 }
1045
1046 /* extract the host portion of the UNC string */
1047 static char *
1048 extract_hostname(const char *unc)
1049 {
1050         const char *src;
1051         char *dst, *delim;
1052         unsigned int len;
1053
1054         /* skip double chars at beginning of string */
1055         /* BB: check validity of these bytes? */
1056         src = unc + 2;
1057
1058         /* delimiter between hostname and sharename is always '\\' now */
1059         delim = strchr(src, '\\');
1060         if (!delim)
1061                 return ERR_PTR(-EINVAL);
1062
1063         len = delim - src;
1064         dst = kmalloc((len + 1), GFP_KERNEL);
1065         if (dst == NULL)
1066                 return ERR_PTR(-ENOMEM);
1067
1068         memcpy(dst, src, len);
1069         dst[len] = '\0';
1070
1071         return dst;
1072 }
1073
1074 static int get_option_ul(substring_t args[], unsigned long *option)
1075 {
1076         int rc;
1077         char *string;
1078
1079         string = match_strdup(args);
1080         if (string == NULL)
1081                 return -ENOMEM;
1082         rc = kstrtoul(string, 0, option);
1083         kfree(string);
1084
1085         return rc;
1086 }
1087
1088 static int get_option_uid(substring_t args[], kuid_t *result)
1089 {
1090         unsigned long value;
1091         kuid_t uid;
1092         int rc;
1093
1094         rc = get_option_ul(args, &value);
1095         if (rc)
1096                 return rc;
1097
1098         uid = make_kuid(current_user_ns(), value);
1099         if (!uid_valid(uid))
1100                 return -EINVAL;
1101
1102         *result = uid;
1103         return 0;
1104 }
1105
1106 static int get_option_gid(substring_t args[], kgid_t *result)
1107 {
1108         unsigned long value;
1109         kgid_t gid;
1110         int rc;
1111
1112         rc = get_option_ul(args, &value);
1113         if (rc)
1114                 return rc;
1115
1116         gid = make_kgid(current_user_ns(), value);
1117         if (!gid_valid(gid))
1118                 return -EINVAL;
1119
1120         *result = gid;
1121         return 0;
1122 }
1123
1124 static int cifs_parse_security_flavors(char *value,
1125                                        struct smb_vol *vol)
1126 {
1127
1128         substring_t args[MAX_OPT_ARGS];
1129
1130         /*
1131          * With mount options, the last one should win. Reset any existing
1132          * settings back to default.
1133          */
1134         vol->sectype = Unspecified;
1135         vol->sign = false;
1136
1137         switch (match_token(value, cifs_secflavor_tokens, args)) {
1138         case Opt_sec_krb5p:
1139                 cifs_dbg(VFS, "sec=krb5p is not supported!\n");
1140                 return 1;
1141         case Opt_sec_krb5i:
1142                 vol->sign = true;
1143                 /* Fallthrough */
1144         case Opt_sec_krb5:
1145                 vol->sectype = Kerberos;
1146                 break;
1147         case Opt_sec_ntlmsspi:
1148                 vol->sign = true;
1149                 /* Fallthrough */
1150         case Opt_sec_ntlmssp:
1151                 vol->sectype = RawNTLMSSP;
1152                 break;
1153         case Opt_sec_ntlmi:
1154                 vol->sign = true;
1155                 /* Fallthrough */
1156         case Opt_ntlm:
1157                 vol->sectype = NTLM;
1158                 break;
1159         case Opt_sec_ntlmv2i:
1160                 vol->sign = true;
1161                 /* Fallthrough */
1162         case Opt_sec_ntlmv2:
1163                 vol->sectype = NTLMv2;
1164                 break;
1165 #ifdef CONFIG_CIFS_WEAK_PW_HASH
1166         case Opt_sec_lanman:
1167                 vol->sectype = LANMAN;
1168                 break;
1169 #endif
1170         case Opt_sec_none:
1171                 vol->nullauth = 1;
1172                 break;
1173         default:
1174                 cifs_dbg(VFS, "bad security option: %s\n", value);
1175                 return 1;
1176         }
1177
1178         return 0;
1179 }
1180
1181 static int
1182 cifs_parse_cache_flavor(char *value, struct smb_vol *vol)
1183 {
1184         substring_t args[MAX_OPT_ARGS];
1185
1186         switch (match_token(value, cifs_cacheflavor_tokens, args)) {
1187         case Opt_cache_loose:
1188                 vol->direct_io = false;
1189                 vol->strict_io = false;
1190                 break;
1191         case Opt_cache_strict:
1192                 vol->direct_io = false;
1193                 vol->strict_io = true;
1194                 break;
1195         case Opt_cache_none:
1196                 vol->direct_io = true;
1197                 vol->strict_io = false;
1198                 break;
1199         default:
1200                 cifs_dbg(VFS, "bad cache= option: %s\n", value);
1201                 return 1;
1202         }
1203         return 0;
1204 }
1205
1206 static int
1207 cifs_parse_smb_version(char *value, struct smb_vol *vol)
1208 {
1209         substring_t args[MAX_OPT_ARGS];
1210
1211         switch (match_token(value, cifs_smb_version_tokens, args)) {
1212 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1213         case Smb_1:
1214                 vol->ops = &smb1_operations;
1215                 vol->vals = &smb1_values;
1216                 break;
1217         case Smb_20:
1218                 vol->ops = &smb20_operations;
1219                 vol->vals = &smb20_values;
1220                 break;
1221 #else
1222         case Smb_1:
1223                 cifs_dbg(VFS, "vers=1.0 (cifs) mount not permitted when legacy dialects disabled\n");
1224                 return 1;
1225         case Smb_20:
1226                 cifs_dbg(VFS, "vers=2.0 mount not permitted when legacy dialects disabled\n");
1227                 return 1;
1228 #endif /* CIFS_ALLOW_INSECURE_LEGACY */
1229         case Smb_21:
1230                 vol->ops = &smb21_operations;
1231                 vol->vals = &smb21_values;
1232                 break;
1233         case Smb_30:
1234                 vol->ops = &smb30_operations;
1235                 vol->vals = &smb30_values;
1236                 break;
1237         case Smb_302:
1238                 vol->ops = &smb30_operations; /* currently identical with 3.0 */
1239                 vol->vals = &smb302_values;
1240                 break;
1241 #ifdef CONFIG_CIFS_SMB311
1242         case Smb_311:
1243                 vol->ops = &smb311_operations;
1244                 vol->vals = &smb311_values;
1245                 break;
1246 #endif /* SMB311 */
1247         case Smb_3any:
1248                 vol->ops = &smb30_operations; /* currently identical with 3.0 */
1249                 vol->vals = &smb3any_values;
1250                 break;
1251         case Smb_default:
1252                 vol->ops = &smb30_operations; /* currently identical with 3.0 */
1253                 vol->vals = &smbdefault_values;
1254                 break;
1255         default:
1256                 cifs_dbg(VFS, "Unknown vers= option specified: %s\n", value);
1257                 return 1;
1258         }
1259         return 0;
1260 }
1261
1262 /*
1263  * Parse a devname into substrings and populate the vol->UNC and vol->prepath
1264  * fields with the result. Returns 0 on success and an error otherwise.
1265  */
1266 static int
1267 cifs_parse_devname(const char *devname, struct smb_vol *vol)
1268 {
1269         char *pos;
1270         const char *delims = "/\\";
1271         size_t len;
1272
1273         if (unlikely(!devname || !*devname)) {
1274                 cifs_dbg(VFS, "Device name not specified.\n");
1275                 return -EINVAL;
1276         }
1277
1278         /* make sure we have a valid UNC double delimiter prefix */
1279         len = strspn(devname, delims);
1280         if (len != 2)
1281                 return -EINVAL;
1282
1283         /* find delimiter between host and sharename */
1284         pos = strpbrk(devname + 2, delims);
1285         if (!pos)
1286                 return -EINVAL;
1287
1288         /* skip past delimiter */
1289         ++pos;
1290
1291         /* now go until next delimiter or end of string */
1292         len = strcspn(pos, delims);
1293
1294         /* move "pos" up to delimiter or NULL */
1295         pos += len;
1296         vol->UNC = kstrndup(devname, pos - devname, GFP_KERNEL);
1297         if (!vol->UNC)
1298                 return -ENOMEM;
1299
1300         convert_delimiter(vol->UNC, '\\');
1301
1302         /* skip any delimiter */
1303         if (*pos == '/' || *pos == '\\')
1304                 pos++;
1305
1306         /* If pos is NULL then no prepath */
1307         if (!*pos)
1308                 return 0;
1309
1310         vol->prepath = kstrdup(pos, GFP_KERNEL);
1311         if (!vol->prepath)
1312                 return -ENOMEM;
1313
1314         return 0;
1315 }
1316
1317 static int
1318 cifs_parse_mount_options(const char *mountdata, const char *devname,
1319                          struct smb_vol *vol)
1320 {
1321         char *data, *end;
1322         char *mountdata_copy = NULL, *options;
1323         unsigned int  temp_len, i, j;
1324         char separator[2];
1325         short int override_uid = -1;
1326         short int override_gid = -1;
1327         bool uid_specified = false;
1328         bool gid_specified = false;
1329         bool sloppy = false;
1330         char *invalid = NULL;
1331         char *nodename = utsname()->nodename;
1332         char *string = NULL;
1333         char *tmp_end, *value;
1334         char delim;
1335         bool got_ip = false;
1336         bool got_version = false;
1337         unsigned short port = 0;
1338         struct sockaddr *dstaddr = (struct sockaddr *)&vol->dstaddr;
1339
1340         separator[0] = ',';
1341         separator[1] = 0;
1342         delim = separator[0];
1343
1344         /* ensure we always start with zeroed-out smb_vol */
1345         memset(vol, 0, sizeof(*vol));
1346
1347         /*
1348          * does not have to be perfect mapping since field is
1349          * informational, only used for servers that do not support
1350          * port 445 and it can be overridden at mount time
1351          */
1352         memset(vol->source_rfc1001_name, 0x20, RFC1001_NAME_LEN);
1353         for (i = 0; i < strnlen(nodename, RFC1001_NAME_LEN); i++)
1354                 vol->source_rfc1001_name[i] = toupper(nodename[i]);
1355
1356         vol->source_rfc1001_name[RFC1001_NAME_LEN] = 0;
1357         /* null target name indicates to use *SMBSERVR default called name
1358            if we end up sending RFC1001 session initialize */
1359         vol->target_rfc1001_name[0] = 0;
1360         vol->cred_uid = current_uid();
1361         vol->linux_uid = current_uid();
1362         vol->linux_gid = current_gid();
1363
1364         /*
1365          * default to SFM style remapping of seven reserved characters
1366          * unless user overrides it or we negotiate CIFS POSIX where
1367          * it is unnecessary.  Can not simultaneously use more than one mapping
1368          * since then readdir could list files that open could not open
1369          */
1370         vol->remap = true;
1371
1372         /* default to only allowing write access to owner of the mount */
1373         vol->dir_mode = vol->file_mode = S_IRUGO | S_IXUGO | S_IWUSR;
1374
1375         /* vol->retry default is 0 (i.e. "soft" limited retry not hard retry) */
1376         /* default is always to request posix paths. */
1377         vol->posix_paths = 1;
1378         /* default to using server inode numbers where available */
1379         vol->server_ino = 1;
1380
1381         /* default is to use strict cifs caching semantics */
1382         vol->strict_io = true;
1383
1384         vol->actimeo = CIFS_DEF_ACTIMEO;
1385
1386         /* offer SMB2.1 and later (SMB3 etc). Secure and widely accepted */
1387         vol->ops = &smb30_operations;
1388         vol->vals = &smbdefault_values;
1389
1390         vol->echo_interval = SMB_ECHO_INTERVAL_DEFAULT;
1391
1392         if (!mountdata)
1393                 goto cifs_parse_mount_err;
1394
1395         mountdata_copy = kstrndup(mountdata, PAGE_SIZE, GFP_KERNEL);
1396         if (!mountdata_copy)
1397                 goto cifs_parse_mount_err;
1398
1399         options = mountdata_copy;
1400         end = options + strlen(options);
1401
1402         if (strncmp(options, "sep=", 4) == 0) {
1403                 if (options[4] != 0) {
1404                         separator[0] = options[4];
1405                         options += 5;
1406                 } else {
1407                         cifs_dbg(FYI, "Null separator not allowed\n");
1408                 }
1409         }
1410         vol->backupuid_specified = false; /* no backup intent for a user */
1411         vol->backupgid_specified = false; /* no backup intent for a group */
1412
1413         switch (cifs_parse_devname(devname, vol)) {
1414         case 0:
1415                 break;
1416         case -ENOMEM:
1417                 cifs_dbg(VFS, "Unable to allocate memory for devname.\n");
1418                 goto cifs_parse_mount_err;
1419         case -EINVAL:
1420                 cifs_dbg(VFS, "Malformed UNC in devname.\n");
1421                 goto cifs_parse_mount_err;
1422         default:
1423                 cifs_dbg(VFS, "Unknown error parsing devname.\n");
1424                 goto cifs_parse_mount_err;
1425         }
1426
1427         while ((data = strsep(&options, separator)) != NULL) {
1428                 substring_t args[MAX_OPT_ARGS];
1429                 unsigned long option;
1430                 int token;
1431
1432                 if (!*data)
1433                         continue;
1434
1435                 token = match_token(data, cifs_mount_option_tokens, args);
1436
1437                 switch (token) {
1438
1439                 /* Ingnore the following */
1440                 case Opt_ignore:
1441                         break;
1442
1443                 /* Boolean values */
1444                 case Opt_user_xattr:
1445                         vol->no_xattr = 0;
1446                         break;
1447                 case Opt_nouser_xattr:
1448                         vol->no_xattr = 1;
1449                         break;
1450                 case Opt_forceuid:
1451                         override_uid = 1;
1452                         break;
1453                 case Opt_noforceuid:
1454                         override_uid = 0;
1455                         break;
1456                 case Opt_forcegid:
1457                         override_gid = 1;
1458                         break;
1459                 case Opt_noforcegid:
1460                         override_gid = 0;
1461                         break;
1462                 case Opt_noblocksend:
1463                         vol->noblocksnd = 1;
1464                         break;
1465                 case Opt_noautotune:
1466                         vol->noautotune = 1;
1467                         break;
1468                 case Opt_hard:
1469                         vol->retry = 1;
1470                         break;
1471                 case Opt_soft:
1472                         vol->retry = 0;
1473                         break;
1474                 case Opt_perm:
1475                         vol->noperm = 0;
1476                         break;
1477                 case Opt_noperm:
1478                         vol->noperm = 1;
1479                         break;
1480                 case Opt_mapchars:
1481                         vol->sfu_remap = true;
1482                         vol->remap = false; /* disable SFM mapping */
1483                         break;
1484                 case Opt_nomapchars:
1485                         vol->sfu_remap = false;
1486                         break;
1487                 case Opt_mapposix:
1488                         vol->remap = true;
1489                         vol->sfu_remap = false; /* disable SFU mapping */
1490                         break;
1491                 case Opt_nomapposix:
1492                         vol->remap = false;
1493                         break;
1494                 case Opt_sfu:
1495                         vol->sfu_emul = 1;
1496                         break;
1497                 case Opt_nosfu:
1498                         vol->sfu_emul = 0;
1499                         break;
1500                 case Opt_nodfs:
1501                         vol->nodfs = 1;
1502                         break;
1503                 case Opt_posixpaths:
1504                         vol->posix_paths = 1;
1505                         break;
1506                 case Opt_noposixpaths:
1507                         vol->posix_paths = 0;
1508                         break;
1509                 case Opt_nounix:
1510                         vol->no_linux_ext = 1;
1511                         break;
1512                 case Opt_nocase:
1513                         vol->nocase = 1;
1514                         break;
1515                 case Opt_brl:
1516                         vol->nobrl =  0;
1517                         break;
1518                 case Opt_nobrl:
1519                         vol->nobrl =  1;
1520                         /*
1521                          * turn off mandatory locking in mode
1522                          * if remote locking is turned off since the
1523                          * local vfs will do advisory
1524                          */
1525                         if (vol->file_mode ==
1526                                 (S_IALLUGO & ~(S_ISUID | S_IXGRP)))
1527                                 vol->file_mode = S_IALLUGO;
1528                         break;
1529                 case Opt_forcemandatorylock:
1530                         vol->mand_lock = 1;
1531                         break;
1532                 case Opt_setuids:
1533                         vol->setuids = 1;
1534                         break;
1535                 case Opt_nosetuids:
1536                         vol->setuids = 0;
1537                         break;
1538                 case Opt_setuidfromacl:
1539                         vol->setuidfromacl = 1;
1540                         break;
1541                 case Opt_dynperm:
1542                         vol->dynperm = true;
1543                         break;
1544                 case Opt_nodynperm:
1545                         vol->dynperm = false;
1546                         break;
1547                 case Opt_nohard:
1548                         vol->retry = 0;
1549                         break;
1550                 case Opt_nosoft:
1551                         vol->retry = 1;
1552                         break;
1553                 case Opt_nointr:
1554                         vol->intr = 0;
1555                         break;
1556                 case Opt_intr:
1557                         vol->intr = 1;
1558                         break;
1559                 case Opt_nostrictsync:
1560                         vol->nostrictsync = 1;
1561                         break;
1562                 case Opt_strictsync:
1563                         vol->nostrictsync = 0;
1564                         break;
1565                 case Opt_serverino:
1566                         vol->server_ino = 1;
1567                         break;
1568                 case Opt_noserverino:
1569                         vol->server_ino = 0;
1570                         break;
1571                 case Opt_rwpidforward:
1572                         vol->rwpidforward = 1;
1573                         break;
1574                 case Opt_cifsacl:
1575                         vol->cifs_acl = 1;
1576                         break;
1577                 case Opt_nocifsacl:
1578                         vol->cifs_acl = 0;
1579                         break;
1580                 case Opt_acl:
1581                         vol->no_psx_acl = 0;
1582                         break;
1583                 case Opt_noacl:
1584                         vol->no_psx_acl = 1;
1585                         break;
1586                 case Opt_locallease:
1587                         vol->local_lease = 1;
1588                         break;
1589                 case Opt_sign:
1590                         vol->sign = true;
1591                         break;
1592                 case Opt_seal:
1593                         /* we do not do the following in secFlags because seal
1594                          * is a per tree connection (mount) not a per socket
1595                          * or per-smb connection option in the protocol
1596                          * vol->secFlg |= CIFSSEC_MUST_SEAL;
1597                          */
1598                         vol->seal = 1;
1599                         break;
1600                 case Opt_noac:
1601                         pr_warn("CIFS: Mount option noac not supported. Instead set /proc/fs/cifs/LookupCacheEnabled to 0\n");
1602                         break;
1603                 case Opt_fsc:
1604 #ifndef CONFIG_CIFS_FSCACHE
1605                         cifs_dbg(VFS, "FS-Cache support needs CONFIG_CIFS_FSCACHE kernel config option set\n");
1606                         goto cifs_parse_mount_err;
1607 #endif
1608                         vol->fsc = true;
1609                         break;
1610                 case Opt_mfsymlinks:
1611                         vol->mfsymlinks = true;
1612                         break;
1613                 case Opt_multiuser:
1614                         vol->multiuser = true;
1615                         break;
1616                 case Opt_sloppy:
1617                         sloppy = true;
1618                         break;
1619                 case Opt_nosharesock:
1620                         vol->nosharesock = true;
1621                         break;
1622                 case Opt_nopersistent:
1623                         vol->nopersistent = true;
1624                         if (vol->persistent) {
1625                                 cifs_dbg(VFS,
1626                                   "persistenthandles mount options conflict\n");
1627                                 goto cifs_parse_mount_err;
1628                         }
1629                         break;
1630                 case Opt_persistent:
1631                         vol->persistent = true;
1632                         if ((vol->nopersistent) || (vol->resilient)) {
1633                                 cifs_dbg(VFS,
1634                                   "persistenthandles mount options conflict\n");
1635                                 goto cifs_parse_mount_err;
1636                         }
1637                         break;
1638                 case Opt_resilient:
1639                         vol->resilient = true;
1640                         if (vol->persistent) {
1641                                 cifs_dbg(VFS,
1642                                   "persistenthandles mount options conflict\n");
1643                                 goto cifs_parse_mount_err;
1644                         }
1645                         break;
1646                 case Opt_noresilient:
1647                         vol->resilient = false; /* already the default */
1648                         break;
1649                 case Opt_domainauto:
1650                         vol->domainauto = true;
1651                         break;
1652
1653                 /* Numeric Values */
1654                 case Opt_backupuid:
1655                         if (get_option_uid(args, &vol->backupuid)) {
1656                                 cifs_dbg(VFS, "%s: Invalid backupuid value\n",
1657                                          __func__);
1658                                 goto cifs_parse_mount_err;
1659                         }
1660                         vol->backupuid_specified = true;
1661                         break;
1662                 case Opt_backupgid:
1663                         if (get_option_gid(args, &vol->backupgid)) {
1664                                 cifs_dbg(VFS, "%s: Invalid backupgid value\n",
1665                                          __func__);
1666                                 goto cifs_parse_mount_err;
1667                         }
1668                         vol->backupgid_specified = true;
1669                         break;
1670                 case Opt_uid:
1671                         if (get_option_uid(args, &vol->linux_uid)) {
1672                                 cifs_dbg(VFS, "%s: Invalid uid value\n",
1673                                          __func__);
1674                                 goto cifs_parse_mount_err;
1675                         }
1676                         uid_specified = true;
1677                         break;
1678                 case Opt_cruid:
1679                         if (get_option_uid(args, &vol->cred_uid)) {
1680                                 cifs_dbg(VFS, "%s: Invalid cruid value\n",
1681                                          __func__);
1682                                 goto cifs_parse_mount_err;
1683                         }
1684                         break;
1685                 case Opt_gid:
1686                         if (get_option_gid(args, &vol->linux_gid)) {
1687                                 cifs_dbg(VFS, "%s: Invalid gid value\n",
1688                                          __func__);
1689                                 goto cifs_parse_mount_err;
1690                         }
1691                         gid_specified = true;
1692                         break;
1693                 case Opt_file_mode:
1694                         if (get_option_ul(args, &option)) {
1695                                 cifs_dbg(VFS, "%s: Invalid file_mode value\n",
1696                                          __func__);
1697                                 goto cifs_parse_mount_err;
1698                         }
1699                         vol->file_mode = option;
1700                         break;
1701                 case Opt_dirmode:
1702                         if (get_option_ul(args, &option)) {
1703                                 cifs_dbg(VFS, "%s: Invalid dir_mode value\n",
1704                                          __func__);
1705                                 goto cifs_parse_mount_err;
1706                         }
1707                         vol->dir_mode = option;
1708                         break;
1709                 case Opt_port:
1710                         if (get_option_ul(args, &option) ||
1711                             option > USHRT_MAX) {
1712                                 cifs_dbg(VFS, "%s: Invalid port value\n",
1713                                          __func__);
1714                                 goto cifs_parse_mount_err;
1715                         }
1716                         port = (unsigned short)option;
1717                         break;
1718                 case Opt_rsize:
1719                         if (get_option_ul(args, &option)) {
1720                                 cifs_dbg(VFS, "%s: Invalid rsize value\n",
1721                                          __func__);
1722                                 goto cifs_parse_mount_err;
1723                         }
1724                         vol->rsize = option;
1725                         break;
1726                 case Opt_wsize:
1727                         if (get_option_ul(args, &option)) {
1728                                 cifs_dbg(VFS, "%s: Invalid wsize value\n",
1729                                          __func__);
1730                                 goto cifs_parse_mount_err;
1731                         }
1732                         vol->wsize = option;
1733                         break;
1734                 case Opt_actimeo:
1735                         if (get_option_ul(args, &option)) {
1736                                 cifs_dbg(VFS, "%s: Invalid actimeo value\n",
1737                                          __func__);
1738                                 goto cifs_parse_mount_err;
1739                         }
1740                         vol->actimeo = HZ * option;
1741                         if (vol->actimeo > CIFS_MAX_ACTIMEO) {
1742                                 cifs_dbg(VFS, "attribute cache timeout too large\n");
1743                                 goto cifs_parse_mount_err;
1744                         }
1745                         break;
1746                 case Opt_echo_interval:
1747                         if (get_option_ul(args, &option)) {
1748                                 cifs_dbg(VFS, "%s: Invalid echo interval value\n",
1749                                          __func__);
1750                                 goto cifs_parse_mount_err;
1751                         }
1752                         vol->echo_interval = option;
1753                         break;
1754                 case Opt_snapshot:
1755                         if (get_option_ul(args, &option)) {
1756                                 cifs_dbg(VFS, "%s: Invalid snapshot time\n",
1757                                          __func__);
1758                                 goto cifs_parse_mount_err;
1759                         }
1760                         vol->snapshot_time = option;
1761                         break;
1762                 case Opt_max_credits:
1763                         if (get_option_ul(args, &option) || (option < 20) ||
1764                             (option > 60000)) {
1765                                 cifs_dbg(VFS, "%s: Invalid max_credits value\n",
1766                                          __func__);
1767                                 goto cifs_parse_mount_err;
1768                         }
1769                         vol->max_credits = option;
1770                         break;
1771
1772                 /* String Arguments */
1773
1774                 case Opt_blank_user:
1775                         /* null user, ie. anonymous authentication */
1776                         vol->nullauth = 1;
1777                         vol->username = NULL;
1778                         break;
1779                 case Opt_user:
1780                         string = match_strdup(args);
1781                         if (string == NULL)
1782                                 goto out_nomem;
1783
1784                         if (strnlen(string, CIFS_MAX_USERNAME_LEN) >
1785                                                         CIFS_MAX_USERNAME_LEN) {
1786                                 pr_warn("CIFS: username too long\n");
1787                                 goto cifs_parse_mount_err;
1788                         }
1789
1790                         kfree(vol->username);
1791                         vol->username = kstrdup(string, GFP_KERNEL);
1792                         if (!vol->username)
1793                                 goto cifs_parse_mount_err;
1794                         break;
1795                 case Opt_blank_pass:
1796                         /* passwords have to be handled differently
1797                          * to allow the character used for deliminator
1798                          * to be passed within them
1799                          */
1800
1801                         /*
1802                          * Check if this is a case where the  password
1803                          * starts with a delimiter
1804                          */
1805                         tmp_end = strchr(data, '=');
1806                         tmp_end++;
1807                         if (!(tmp_end < end && tmp_end[1] == delim)) {
1808                                 /* No it is not. Set the password to NULL */
1809                                 kzfree(vol->password);
1810                                 vol->password = NULL;
1811                                 break;
1812                         }
1813                         /* Yes it is. Drop down to Opt_pass below.*/
1814                 case Opt_pass:
1815                         /* Obtain the value string */
1816                         value = strchr(data, '=');
1817                         value++;
1818
1819                         /* Set tmp_end to end of the string */
1820                         tmp_end = (char *) value + strlen(value);
1821
1822                         /* Check if following character is the deliminator
1823                          * If yes, we have encountered a double deliminator
1824                          * reset the NULL character to the deliminator
1825                          */
1826                         if (tmp_end < end && tmp_end[1] == delim) {
1827                                 tmp_end[0] = delim;
1828
1829                                 /* Keep iterating until we get to a single
1830                                  * deliminator OR the end
1831                                  */
1832                                 while ((tmp_end = strchr(tmp_end, delim))
1833                                         != NULL && (tmp_end[1] == delim)) {
1834                                                 tmp_end = (char *) &tmp_end[2];
1835                                 }
1836
1837                                 /* Reset var options to point to next element */
1838                                 if (tmp_end) {
1839                                         tmp_end[0] = '\0';
1840                                         options = (char *) &tmp_end[1];
1841                                 } else
1842                                         /* Reached the end of the mount option
1843                                          * string */
1844                                         options = end;
1845                         }
1846
1847                         kzfree(vol->password);
1848                         /* Now build new password string */
1849                         temp_len = strlen(value);
1850                         vol->password = kzalloc(temp_len+1, GFP_KERNEL);
1851                         if (vol->password == NULL) {
1852                                 pr_warn("CIFS: no memory for password\n");
1853                                 goto cifs_parse_mount_err;
1854                         }
1855
1856                         for (i = 0, j = 0; i < temp_len; i++, j++) {
1857                                 vol->password[j] = value[i];
1858                                 if ((value[i] == delim) &&
1859                                      value[i+1] == delim)
1860                                         /* skip the second deliminator */
1861                                         i++;
1862                         }
1863                         vol->password[j] = '\0';
1864                         break;
1865                 case Opt_blank_ip:
1866                         /* FIXME: should this be an error instead? */
1867                         got_ip = false;
1868                         break;
1869                 case Opt_ip:
1870                         string = match_strdup(args);
1871                         if (string == NULL)
1872                                 goto out_nomem;
1873
1874                         if (!cifs_convert_address(dstaddr, string,
1875                                         strlen(string))) {
1876                                 pr_err("CIFS: bad ip= option (%s).\n", string);
1877                                 goto cifs_parse_mount_err;
1878                         }
1879                         got_ip = true;
1880                         break;
1881                 case Opt_domain:
1882                         string = match_strdup(args);
1883                         if (string == NULL)
1884                                 goto out_nomem;
1885
1886                         if (strnlen(string, CIFS_MAX_DOMAINNAME_LEN)
1887                                         == CIFS_MAX_DOMAINNAME_LEN) {
1888                                 pr_warn("CIFS: domain name too long\n");
1889                                 goto cifs_parse_mount_err;
1890                         }
1891
1892                         kfree(vol->domainname);
1893                         vol->domainname = kstrdup(string, GFP_KERNEL);
1894                         if (!vol->domainname) {
1895                                 pr_warn("CIFS: no memory for domainname\n");
1896                                 goto cifs_parse_mount_err;
1897                         }
1898                         cifs_dbg(FYI, "Domain name set\n");
1899                         break;
1900                 case Opt_srcaddr:
1901                         string = match_strdup(args);
1902                         if (string == NULL)
1903                                 goto out_nomem;
1904
1905                         if (!cifs_convert_address(
1906                                         (struct sockaddr *)&vol->srcaddr,
1907                                         string, strlen(string))) {
1908                                 pr_warn("CIFS: Could not parse srcaddr: %s\n",
1909                                         string);
1910                                 goto cifs_parse_mount_err;
1911                         }
1912                         break;
1913                 case Opt_iocharset:
1914                         string = match_strdup(args);
1915                         if (string == NULL)
1916                                 goto out_nomem;
1917
1918                         if (strnlen(string, 1024) >= 65) {
1919                                 pr_warn("CIFS: iocharset name too long.\n");
1920                                 goto cifs_parse_mount_err;
1921                         }
1922
1923                          if (strncasecmp(string, "default", 7) != 0) {
1924                                 kfree(vol->iocharset);
1925                                 vol->iocharset = kstrdup(string,
1926                                                          GFP_KERNEL);
1927                                 if (!vol->iocharset) {
1928                                         pr_warn("CIFS: no memory for charset\n");
1929                                         goto cifs_parse_mount_err;
1930                                 }
1931                         }
1932                         /* if iocharset not set then load_nls_default
1933                          * is used by caller
1934                          */
1935                          cifs_dbg(FYI, "iocharset set to %s\n", string);
1936                         break;
1937                 case Opt_netbiosname:
1938                         string = match_strdup(args);
1939                         if (string == NULL)
1940                                 goto out_nomem;
1941
1942                         memset(vol->source_rfc1001_name, 0x20,
1943                                 RFC1001_NAME_LEN);
1944                         /*
1945                          * FIXME: are there cases in which a comma can
1946                          * be valid in workstation netbios name (and
1947                          * need special handling)?
1948                          */
1949                         for (i = 0; i < RFC1001_NAME_LEN; i++) {
1950                                 /* don't ucase netbiosname for user */
1951                                 if (string[i] == 0)
1952                                         break;
1953                                 vol->source_rfc1001_name[i] = string[i];
1954                         }
1955                         /* The string has 16th byte zero still from
1956                          * set at top of the function
1957                          */
1958                         if (i == RFC1001_NAME_LEN && string[i] != 0)
1959                                 pr_warn("CIFS: netbiosname longer than 15 truncated.\n");
1960                         break;
1961                 case Opt_servern:
1962                         /* servernetbiosname specified override *SMBSERVER */
1963                         string = match_strdup(args);
1964                         if (string == NULL)
1965                                 goto out_nomem;
1966
1967                         /* last byte, type, is 0x20 for servr type */
1968                         memset(vol->target_rfc1001_name, 0x20,
1969                                 RFC1001_NAME_LEN_WITH_NULL);
1970
1971                         /* BB are there cases in which a comma can be
1972                            valid in this workstation netbios name
1973                            (and need special handling)? */
1974
1975                         /* user or mount helper must uppercase the
1976                            netbios name */
1977                         for (i = 0; i < 15; i++) {
1978                                 if (string[i] == 0)
1979                                         break;
1980                                 vol->target_rfc1001_name[i] = string[i];
1981                         }
1982                         /* The string has 16th byte zero still from
1983                            set at top of the function  */
1984                         if (i == RFC1001_NAME_LEN && string[i] != 0)
1985                                 pr_warn("CIFS: server netbiosname longer than 15 truncated.\n");
1986                         break;
1987                 case Opt_ver:
1988                         /* version of mount userspace tools, not dialect */
1989                         string = match_strdup(args);
1990                         if (string == NULL)
1991                                 goto out_nomem;
1992
1993                         /* If interface changes in mount.cifs bump to new ver */
1994                         if (strncasecmp(string, "1", 1) == 0) {
1995                                 if (strlen(string) > 1) {
1996                                         pr_warn("Bad mount helper ver=%s. Did "
1997                                                 "you want SMB1 (CIFS) dialect "
1998                                                 "and mean to type vers=1.0 "
1999                                                 "instead?\n", string);
2000                                         goto cifs_parse_mount_err;
2001                                 }
2002                                 /* This is the default */
2003                                 break;
2004                         }
2005                         /* For all other value, error */
2006                         pr_warn("CIFS: Invalid mount helper version specified\n");
2007                         goto cifs_parse_mount_err;
2008                 case Opt_vers:
2009                         /* protocol version (dialect) */
2010                         string = match_strdup(args);
2011                         if (string == NULL)
2012                                 goto out_nomem;
2013
2014                         if (cifs_parse_smb_version(string, vol) != 0)
2015                                 goto cifs_parse_mount_err;
2016                         got_version = true;
2017                         break;
2018                 case Opt_sec:
2019                         string = match_strdup(args);
2020                         if (string == NULL)
2021                                 goto out_nomem;
2022
2023                         if (cifs_parse_security_flavors(string, vol) != 0)
2024                                 goto cifs_parse_mount_err;
2025                         break;
2026                 case Opt_cache:
2027                         string = match_strdup(args);
2028                         if (string == NULL)
2029                                 goto out_nomem;
2030
2031                         if (cifs_parse_cache_flavor(string, vol) != 0)
2032                                 goto cifs_parse_mount_err;
2033                         break;
2034                 default:
2035                         /*
2036                          * An option we don't recognize. Save it off for later
2037                          * if we haven't already found one
2038                          */
2039                         if (!invalid)
2040                                 invalid = data;
2041                         break;
2042                 }
2043                 /* Free up any allocated string */
2044                 kfree(string);
2045                 string = NULL;
2046         }
2047
2048         if (!sloppy && invalid) {
2049                 pr_err("CIFS: Unknown mount option \"%s\"\n", invalid);
2050                 goto cifs_parse_mount_err;
2051         }
2052
2053 #ifndef CONFIG_KEYS
2054         /* Muliuser mounts require CONFIG_KEYS support */
2055         if (vol->multiuser) {
2056                 cifs_dbg(VFS, "Multiuser mounts require kernels with CONFIG_KEYS enabled\n");
2057                 goto cifs_parse_mount_err;
2058         }
2059 #endif
2060         if (!vol->UNC) {
2061                 cifs_dbg(VFS, "CIFS mount error: No usable UNC path provided in device string!\n");
2062                 goto cifs_parse_mount_err;
2063         }
2064
2065         /* make sure UNC has a share name */
2066         if (!strchr(vol->UNC + 3, '\\')) {
2067                 cifs_dbg(VFS, "Malformed UNC. Unable to find share name.\n");
2068                 goto cifs_parse_mount_err;
2069         }
2070
2071         if (!got_ip) {
2072                 int len;
2073                 const char *slash;
2074
2075                 /* No ip= option specified? Try to get it from UNC */
2076                 /* Use the address part of the UNC. */
2077                 slash = strchr(&vol->UNC[2], '\\');
2078                 len = slash - &vol->UNC[2];
2079                 if (!cifs_convert_address(dstaddr, &vol->UNC[2], len)) {
2080                         pr_err("Unable to determine destination address.\n");
2081                         goto cifs_parse_mount_err;
2082                 }
2083         }
2084
2085         /* set the port that we got earlier */
2086         cifs_set_port(dstaddr, port);
2087
2088         if (uid_specified)
2089                 vol->override_uid = override_uid;
2090         else if (override_uid == 1)
2091                 pr_notice("CIFS: ignoring forceuid mount option specified with no uid= option.\n");
2092
2093         if (gid_specified)
2094                 vol->override_gid = override_gid;
2095         else if (override_gid == 1)
2096                 pr_notice("CIFS: ignoring forcegid mount option specified with no gid= option.\n");
2097
2098         if (got_version == false)
2099                 pr_warn("No dialect specified on mount. Default has changed to "
2100                         "a more secure dialect, SMB2.1 or later (e.g. SMB3), from CIFS "
2101                         "(SMB1). To use the less secure SMB1 dialect to access "
2102                         "old servers which do not support SMB3 (or SMB2.1) specify vers=1.0"
2103                         " on mount.\n");
2104
2105         kfree(mountdata_copy);
2106         return 0;
2107
2108 out_nomem:
2109         pr_warn("Could not allocate temporary buffer\n");
2110 cifs_parse_mount_err:
2111         kfree(string);
2112         kfree(mountdata_copy);
2113         return 1;
2114 }
2115
2116 /** Returns true if srcaddr isn't specified and rhs isn't
2117  * specified, or if srcaddr is specified and
2118  * matches the IP address of the rhs argument.
2119  */
2120 static bool
2121 srcip_matches(struct sockaddr *srcaddr, struct sockaddr *rhs)
2122 {
2123         switch (srcaddr->sa_family) {
2124         case AF_UNSPEC:
2125                 return (rhs->sa_family == AF_UNSPEC);
2126         case AF_INET: {
2127                 struct sockaddr_in *saddr4 = (struct sockaddr_in *)srcaddr;
2128                 struct sockaddr_in *vaddr4 = (struct sockaddr_in *)rhs;
2129                 return (saddr4->sin_addr.s_addr == vaddr4->sin_addr.s_addr);
2130         }
2131         case AF_INET6: {
2132                 struct sockaddr_in6 *saddr6 = (struct sockaddr_in6 *)srcaddr;
2133                 struct sockaddr_in6 *vaddr6 = (struct sockaddr_in6 *)rhs;
2134                 return ipv6_addr_equal(&saddr6->sin6_addr, &vaddr6->sin6_addr);
2135         }
2136         default:
2137                 WARN_ON(1);
2138                 return false; /* don't expect to be here */
2139         }
2140 }
2141
2142 /*
2143  * If no port is specified in addr structure, we try to match with 445 port
2144  * and if it fails - with 139 ports. It should be called only if address
2145  * families of server and addr are equal.
2146  */
2147 static bool
2148 match_port(struct TCP_Server_Info *server, struct sockaddr *addr)
2149 {
2150         __be16 port, *sport;
2151
2152         switch (addr->sa_family) {
2153         case AF_INET:
2154                 sport = &((struct sockaddr_in *) &server->dstaddr)->sin_port;
2155                 port = ((struct sockaddr_in *) addr)->sin_port;
2156                 break;
2157         case AF_INET6:
2158                 sport = &((struct sockaddr_in6 *) &server->dstaddr)->sin6_port;
2159                 port = ((struct sockaddr_in6 *) addr)->sin6_port;
2160                 break;
2161         default:
2162                 WARN_ON(1);
2163                 return false;
2164         }
2165
2166         if (!port) {
2167                 port = htons(CIFS_PORT);
2168                 if (port == *sport)
2169                         return true;
2170
2171                 port = htons(RFC1001_PORT);
2172         }
2173
2174         return port == *sport;
2175 }
2176
2177 static bool
2178 match_address(struct TCP_Server_Info *server, struct sockaddr *addr,
2179               struct sockaddr *srcaddr)
2180 {
2181         switch (addr->sa_family) {
2182         case AF_INET: {
2183                 struct sockaddr_in *addr4 = (struct sockaddr_in *)addr;
2184                 struct sockaddr_in *srv_addr4 =
2185                                         (struct sockaddr_in *)&server->dstaddr;
2186
2187                 if (addr4->sin_addr.s_addr != srv_addr4->sin_addr.s_addr)
2188                         return false;
2189                 break;
2190         }
2191         case AF_INET6: {
2192                 struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)addr;
2193                 struct sockaddr_in6 *srv_addr6 =
2194                                         (struct sockaddr_in6 *)&server->dstaddr;
2195
2196                 if (!ipv6_addr_equal(&addr6->sin6_addr,
2197                                      &srv_addr6->sin6_addr))
2198                         return false;
2199                 if (addr6->sin6_scope_id != srv_addr6->sin6_scope_id)
2200                         return false;
2201                 break;
2202         }
2203         default:
2204                 WARN_ON(1);
2205                 return false; /* don't expect to be here */
2206         }
2207
2208         if (!srcip_matches(srcaddr, (struct sockaddr *)&server->srcaddr))
2209                 return false;
2210
2211         return true;
2212 }
2213
2214 static bool
2215 match_security(struct TCP_Server_Info *server, struct smb_vol *vol)
2216 {
2217         /*
2218          * The select_sectype function should either return the vol->sectype
2219          * that was specified, or "Unspecified" if that sectype was not
2220          * compatible with the given NEGOTIATE request.
2221          */
2222         if (server->ops->select_sectype(server, vol->sectype)
2223              == Unspecified)
2224                 return false;
2225
2226         /*
2227          * Now check if signing mode is acceptable. No need to check
2228          * global_secflags at this point since if MUST_SIGN is set then
2229          * the server->sign had better be too.
2230          */
2231         if (vol->sign && !server->sign)
2232                 return false;
2233
2234         return true;
2235 }
2236
2237 static int match_server(struct TCP_Server_Info *server, struct smb_vol *vol)
2238 {
2239         struct sockaddr *addr = (struct sockaddr *)&vol->dstaddr;
2240
2241         if (vol->nosharesock)
2242                 return 0;
2243
2244         /* BB update this for smb3any and default case */
2245         if ((server->vals != vol->vals) || (server->ops != vol->ops))
2246                 return 0;
2247
2248         if (!net_eq(cifs_net_ns(server), current->nsproxy->net_ns))
2249                 return 0;
2250
2251         if (!match_address(server, addr,
2252                            (struct sockaddr *)&vol->srcaddr))
2253                 return 0;
2254
2255         if (!match_port(server, addr))
2256                 return 0;
2257
2258         if (!match_security(server, vol))
2259                 return 0;
2260
2261         if (server->echo_interval != vol->echo_interval * HZ)
2262                 return 0;
2263
2264         return 1;
2265 }
2266
2267 static struct TCP_Server_Info *
2268 cifs_find_tcp_session(struct smb_vol *vol)
2269 {
2270         struct TCP_Server_Info *server;
2271
2272         spin_lock(&cifs_tcp_ses_lock);
2273         list_for_each_entry(server, &cifs_tcp_ses_list, tcp_ses_list) {
2274                 if (!match_server(server, vol))
2275                         continue;
2276
2277                 ++server->srv_count;
2278                 spin_unlock(&cifs_tcp_ses_lock);
2279                 cifs_dbg(FYI, "Existing tcp session with server found\n");
2280                 return server;
2281         }
2282         spin_unlock(&cifs_tcp_ses_lock);
2283         return NULL;
2284 }
2285
2286 void
2287 cifs_put_tcp_session(struct TCP_Server_Info *server, int from_reconnect)
2288 {
2289         struct task_struct *task;
2290
2291         spin_lock(&cifs_tcp_ses_lock);
2292         if (--server->srv_count > 0) {
2293                 spin_unlock(&cifs_tcp_ses_lock);
2294                 return;
2295         }
2296
2297         put_net(cifs_net_ns(server));
2298
2299         list_del_init(&server->tcp_ses_list);
2300         spin_unlock(&cifs_tcp_ses_lock);
2301
2302         cancel_delayed_work_sync(&server->echo);
2303
2304         if (from_reconnect)
2305                 /*
2306                  * Avoid deadlock here: reconnect work calls
2307                  * cifs_put_tcp_session() at its end. Need to be sure
2308                  * that reconnect work does nothing with server pointer after
2309                  * that step.
2310                  */
2311                 cancel_delayed_work(&server->reconnect);
2312         else
2313                 cancel_delayed_work_sync(&server->reconnect);
2314
2315         spin_lock(&GlobalMid_Lock);
2316         server->tcpStatus = CifsExiting;
2317         spin_unlock(&GlobalMid_Lock);
2318
2319         cifs_crypto_secmech_release(server);
2320         cifs_fscache_release_client_cookie(server);
2321
2322         kfree(server->session_key.response);
2323         server->session_key.response = NULL;
2324         server->session_key.len = 0;
2325
2326         task = xchg(&server->tsk, NULL);
2327         if (task)
2328                 send_sig(SIGKILL, task, 1);
2329 }
2330
2331 static struct TCP_Server_Info *
2332 cifs_get_tcp_session(struct smb_vol *volume_info)
2333 {
2334         struct TCP_Server_Info *tcp_ses = NULL;
2335         int rc;
2336
2337         cifs_dbg(FYI, "UNC: %s\n", volume_info->UNC);
2338
2339         /* see if we already have a matching tcp_ses */
2340         tcp_ses = cifs_find_tcp_session(volume_info);
2341         if (tcp_ses)
2342                 return tcp_ses;
2343
2344         tcp_ses = kzalloc(sizeof(struct TCP_Server_Info), GFP_KERNEL);
2345         if (!tcp_ses) {
2346                 rc = -ENOMEM;
2347                 goto out_err;
2348         }
2349
2350         tcp_ses->ops = volume_info->ops;
2351         tcp_ses->vals = volume_info->vals;
2352         cifs_set_net_ns(tcp_ses, get_net(current->nsproxy->net_ns));
2353         tcp_ses->hostname = extract_hostname(volume_info->UNC);
2354         if (IS_ERR(tcp_ses->hostname)) {
2355                 rc = PTR_ERR(tcp_ses->hostname);
2356                 goto out_err_crypto_release;
2357         }
2358
2359         tcp_ses->noblocksnd = volume_info->noblocksnd;
2360         tcp_ses->noautotune = volume_info->noautotune;
2361         tcp_ses->tcp_nodelay = volume_info->sockopt_tcp_nodelay;
2362         tcp_ses->in_flight = 0;
2363         tcp_ses->credits = 1;
2364         init_waitqueue_head(&tcp_ses->response_q);
2365         init_waitqueue_head(&tcp_ses->request_q);
2366         INIT_LIST_HEAD(&tcp_ses->pending_mid_q);
2367         mutex_init(&tcp_ses->srv_mutex);
2368         memcpy(tcp_ses->workstation_RFC1001_name,
2369                 volume_info->source_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
2370         memcpy(tcp_ses->server_RFC1001_name,
2371                 volume_info->target_rfc1001_name, RFC1001_NAME_LEN_WITH_NULL);
2372         tcp_ses->session_estab = false;
2373         tcp_ses->sequence_number = 0;
2374         tcp_ses->lstrp = jiffies;
2375         spin_lock_init(&tcp_ses->req_lock);
2376         INIT_LIST_HEAD(&tcp_ses->tcp_ses_list);
2377         INIT_LIST_HEAD(&tcp_ses->smb_ses_list);
2378         INIT_DELAYED_WORK(&tcp_ses->echo, cifs_echo_request);
2379         INIT_DELAYED_WORK(&tcp_ses->reconnect, smb2_reconnect_server);
2380         mutex_init(&tcp_ses->reconnect_mutex);
2381         memcpy(&tcp_ses->srcaddr, &volume_info->srcaddr,
2382                sizeof(tcp_ses->srcaddr));
2383         memcpy(&tcp_ses->dstaddr, &volume_info->dstaddr,
2384                 sizeof(tcp_ses->dstaddr));
2385         generate_random_uuid(tcp_ses->client_guid);
2386         /*
2387          * at this point we are the only ones with the pointer
2388          * to the struct since the kernel thread not created yet
2389          * no need to spinlock this init of tcpStatus or srv_count
2390          */
2391         tcp_ses->tcpStatus = CifsNew;
2392         ++tcp_ses->srv_count;
2393
2394         if (volume_info->echo_interval >= SMB_ECHO_INTERVAL_MIN &&
2395                 volume_info->echo_interval <= SMB_ECHO_INTERVAL_MAX)
2396                 tcp_ses->echo_interval = volume_info->echo_interval * HZ;
2397         else
2398                 tcp_ses->echo_interval = SMB_ECHO_INTERVAL_DEFAULT * HZ;
2399
2400         rc = ip_connect(tcp_ses);
2401         if (rc < 0) {
2402                 cifs_dbg(VFS, "Error connecting to socket. Aborting operation.\n");
2403                 goto out_err_crypto_release;
2404         }
2405
2406         /*
2407          * since we're in a cifs function already, we know that
2408          * this will succeed. No need for try_module_get().
2409          */
2410         __module_get(THIS_MODULE);
2411         tcp_ses->tsk = kthread_run(cifs_demultiplex_thread,
2412                                   tcp_ses, "cifsd");
2413         if (IS_ERR(tcp_ses->tsk)) {
2414                 rc = PTR_ERR(tcp_ses->tsk);
2415                 cifs_dbg(VFS, "error %d create cifsd thread\n", rc);
2416                 module_put(THIS_MODULE);
2417                 goto out_err_crypto_release;
2418         }
2419         tcp_ses->tcpStatus = CifsNeedNegotiate;
2420
2421         /* thread spawned, put it on the list */
2422         spin_lock(&cifs_tcp_ses_lock);
2423         list_add(&tcp_ses->tcp_ses_list, &cifs_tcp_ses_list);
2424         spin_unlock(&cifs_tcp_ses_lock);
2425
2426         cifs_fscache_get_client_cookie(tcp_ses);
2427
2428         /* queue echo request delayed work */
2429         queue_delayed_work(cifsiod_wq, &tcp_ses->echo, tcp_ses->echo_interval);
2430
2431         return tcp_ses;
2432
2433 out_err_crypto_release:
2434         cifs_crypto_secmech_release(tcp_ses);
2435
2436         put_net(cifs_net_ns(tcp_ses));
2437
2438 out_err:
2439         if (tcp_ses) {
2440                 if (!IS_ERR(tcp_ses->hostname))
2441                         kfree(tcp_ses->hostname);
2442                 if (tcp_ses->ssocket)
2443                         sock_release(tcp_ses->ssocket);
2444                 kfree(tcp_ses);
2445         }
2446         return ERR_PTR(rc);
2447 }
2448
2449 static int match_session(struct cifs_ses *ses, struct smb_vol *vol)
2450 {
2451         if (vol->sectype != Unspecified &&
2452             vol->sectype != ses->sectype)
2453                 return 0;
2454
2455         switch (ses->sectype) {
2456         case Kerberos:
2457                 if (!uid_eq(vol->cred_uid, ses->cred_uid))
2458                         return 0;
2459                 break;
2460         default:
2461                 /* NULL username means anonymous session */
2462                 if (ses->user_name == NULL) {
2463                         if (!vol->nullauth)
2464                                 return 0;
2465                         break;
2466                 }
2467
2468                 /* anything else takes username/password */
2469                 if (strncmp(ses->user_name,
2470                             vol->username ? vol->username : "",
2471                             CIFS_MAX_USERNAME_LEN))
2472                         return 0;
2473                 if ((vol->username && strlen(vol->username) != 0) &&
2474                     ses->password != NULL &&
2475                     strncmp(ses->password,
2476                             vol->password ? vol->password : "",
2477                             CIFS_MAX_PASSWORD_LEN))
2478                         return 0;
2479         }
2480         return 1;
2481 }
2482
2483 static struct cifs_ses *
2484 cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb_vol *vol)
2485 {
2486         struct cifs_ses *ses;
2487
2488         spin_lock(&cifs_tcp_ses_lock);
2489         list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) {
2490                 if (ses->status == CifsExiting)
2491                         continue;
2492                 if (!match_session(ses, vol))
2493                         continue;
2494                 ++ses->ses_count;
2495                 spin_unlock(&cifs_tcp_ses_lock);
2496                 return ses;
2497         }
2498         spin_unlock(&cifs_tcp_ses_lock);
2499         return NULL;
2500 }
2501
2502 static void
2503 cifs_put_smb_ses(struct cifs_ses *ses)
2504 {
2505         unsigned int rc, xid;
2506         struct TCP_Server_Info *server = ses->server;
2507
2508         cifs_dbg(FYI, "%s: ses_count=%d\n", __func__, ses->ses_count);
2509
2510         spin_lock(&cifs_tcp_ses_lock);
2511         if (ses->status == CifsExiting) {
2512                 spin_unlock(&cifs_tcp_ses_lock);
2513                 return;
2514         }
2515         if (--ses->ses_count > 0) {
2516                 spin_unlock(&cifs_tcp_ses_lock);
2517                 return;
2518         }
2519         if (ses->status == CifsGood)
2520                 ses->status = CifsExiting;
2521         spin_unlock(&cifs_tcp_ses_lock);
2522
2523         if (ses->status == CifsExiting && server->ops->logoff) {
2524                 xid = get_xid();
2525                 rc = server->ops->logoff(xid, ses);
2526                 if (rc)
2527                         cifs_dbg(VFS, "%s: Session Logoff failure rc=%d\n",
2528                                 __func__, rc);
2529                 _free_xid(xid);
2530         }
2531
2532         spin_lock(&cifs_tcp_ses_lock);
2533         list_del_init(&ses->smb_ses_list);
2534         spin_unlock(&cifs_tcp_ses_lock);
2535
2536         sesInfoFree(ses);
2537         cifs_put_tcp_session(server, 0);
2538 }
2539
2540 #ifdef CONFIG_KEYS
2541
2542 /* strlen("cifs:a:") + CIFS_MAX_DOMAINNAME_LEN + 1 */
2543 #define CIFSCREDS_DESC_SIZE (7 + CIFS_MAX_DOMAINNAME_LEN + 1)
2544
2545 /* Populate username and pw fields from keyring if possible */
2546 static int
2547 cifs_set_cifscreds(struct smb_vol *vol, struct cifs_ses *ses)
2548 {
2549         int rc = 0;
2550         int is_domain = 0;
2551         const char *delim, *payload;
2552         char *desc;
2553         ssize_t len;
2554         struct key *key;
2555         struct TCP_Server_Info *server = ses->server;
2556         struct sockaddr_in *sa;
2557         struct sockaddr_in6 *sa6;
2558         const struct user_key_payload *upayload;
2559
2560         desc = kmalloc(CIFSCREDS_DESC_SIZE, GFP_KERNEL);
2561         if (!desc)
2562                 return -ENOMEM;
2563
2564         /* try to find an address key first */
2565         switch (server->dstaddr.ss_family) {
2566         case AF_INET:
2567                 sa = (struct sockaddr_in *)&server->dstaddr;
2568                 sprintf(desc, "cifs:a:%pI4", &sa->sin_addr.s_addr);
2569                 break;
2570         case AF_INET6:
2571                 sa6 = (struct sockaddr_in6 *)&server->dstaddr;
2572                 sprintf(desc, "cifs:a:%pI6c", &sa6->sin6_addr.s6_addr);
2573                 break;
2574         default:
2575                 cifs_dbg(FYI, "Bad ss_family (%hu)\n",
2576                          server->dstaddr.ss_family);
2577                 rc = -EINVAL;
2578                 goto out_err;
2579         }
2580
2581         cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2582         key = request_key(&key_type_logon, desc, "");
2583         if (IS_ERR(key)) {
2584                 if (!ses->domainName) {
2585                         cifs_dbg(FYI, "domainName is NULL\n");
2586                         rc = PTR_ERR(key);
2587                         goto out_err;
2588                 }
2589
2590                 /* didn't work, try to find a domain key */
2591                 sprintf(desc, "cifs:d:%s", ses->domainName);
2592                 cifs_dbg(FYI, "%s: desc=%s\n", __func__, desc);
2593                 key = request_key(&key_type_logon, desc, "");
2594                 if (IS_ERR(key)) {
2595                         rc = PTR_ERR(key);
2596                         goto out_err;
2597                 }
2598                 is_domain = 1;
2599         }
2600
2601         down_read(&key->sem);
2602         upayload = user_key_payload_locked(key);
2603         if (IS_ERR_OR_NULL(upayload)) {
2604                 rc = upayload ? PTR_ERR(upayload) : -EINVAL;
2605                 goto out_key_put;
2606         }
2607
2608         /* find first : in payload */
2609         payload = upayload->data;
2610         delim = strnchr(payload, upayload->datalen, ':');
2611         cifs_dbg(FYI, "payload=%s\n", payload);
2612         if (!delim) {
2613                 cifs_dbg(FYI, "Unable to find ':' in payload (datalen=%d)\n",
2614                          upayload->datalen);
2615                 rc = -EINVAL;
2616                 goto out_key_put;
2617         }
2618
2619         len = delim - payload;
2620         if (len > CIFS_MAX_USERNAME_LEN || len <= 0) {
2621                 cifs_dbg(FYI, "Bad value from username search (len=%zd)\n",
2622                          len);
2623                 rc = -EINVAL;
2624                 goto out_key_put;
2625         }
2626
2627         vol->username = kstrndup(payload, len, GFP_KERNEL);
2628         if (!vol->username) {
2629                 cifs_dbg(FYI, "Unable to allocate %zd bytes for username\n",
2630                          len);
2631                 rc = -ENOMEM;
2632                 goto out_key_put;
2633         }
2634         cifs_dbg(FYI, "%s: username=%s\n", __func__, vol->username);
2635
2636         len = key->datalen - (len + 1);
2637         if (len > CIFS_MAX_PASSWORD_LEN || len <= 0) {
2638                 cifs_dbg(FYI, "Bad len for password search (len=%zd)\n", len);
2639                 rc = -EINVAL;
2640                 kfree(vol->username);
2641                 vol->username = NULL;
2642                 goto out_key_put;
2643         }
2644
2645         ++delim;
2646         vol->password = kstrndup(delim, len, GFP_KERNEL);
2647         if (!vol->password) {
2648                 cifs_dbg(FYI, "Unable to allocate %zd bytes for password\n",
2649                          len);
2650                 rc = -ENOMEM;
2651                 kfree(vol->username);
2652                 vol->username = NULL;
2653                 goto out_key_put;
2654         }
2655
2656         /*
2657          * If we have a domain key then we must set the domainName in the
2658          * for the request.
2659          */
2660         if (is_domain && ses->domainName) {
2661                 vol->domainname = kstrndup(ses->domainName,
2662                                            strlen(ses->domainName),
2663                                            GFP_KERNEL);
2664                 if (!vol->domainname) {
2665                         cifs_dbg(FYI, "Unable to allocate %zd bytes for "
2666                                  "domain\n", len);
2667                         rc = -ENOMEM;
2668                         kfree(vol->username);
2669                         vol->username = NULL;
2670                         kzfree(vol->password);
2671                         vol->password = NULL;
2672                         goto out_key_put;
2673                 }
2674         }
2675
2676 out_key_put:
2677         up_read(&key->sem);
2678         key_put(key);
2679 out_err:
2680         kfree(desc);
2681         cifs_dbg(FYI, "%s: returning %d\n", __func__, rc);
2682         return rc;
2683 }
2684 #else /* ! CONFIG_KEYS */
2685 static inline int
2686 cifs_set_cifscreds(struct smb_vol *vol __attribute__((unused)),
2687                    struct cifs_ses *ses __attribute__((unused)))
2688 {
2689         return -ENOSYS;
2690 }
2691 #endif /* CONFIG_KEYS */
2692
2693 static struct cifs_ses *
2694 cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info)
2695 {
2696         int rc = 0;
2697         unsigned int xid;
2698         struct cifs_ses *ses;
2699         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
2700         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
2701
2702         xid = get_xid();
2703
2704         ses = cifs_find_smb_ses(server, volume_info);
2705         if (ses) {
2706                 cifs_dbg(FYI, "Existing smb sess found (status=%d)\n",
2707                          ses->status);
2708
2709                 mutex_lock(&ses->session_mutex);
2710                 rc = cifs_negotiate_protocol(xid, ses);
2711                 if (rc) {
2712                         mutex_unlock(&ses->session_mutex);
2713                         /* problem -- put our ses reference */
2714                         cifs_put_smb_ses(ses);
2715                         free_xid(xid);
2716                         return ERR_PTR(rc);
2717                 }
2718                 if (ses->need_reconnect) {
2719                         cifs_dbg(FYI, "Session needs reconnect\n");
2720                         rc = cifs_setup_session(xid, ses,
2721                                                 volume_info->local_nls);
2722                         if (rc) {
2723                                 mutex_unlock(&ses->session_mutex);
2724                                 /* problem -- put our reference */
2725                                 cifs_put_smb_ses(ses);
2726                                 free_xid(xid);
2727                                 return ERR_PTR(rc);
2728                         }
2729                 }
2730                 mutex_unlock(&ses->session_mutex);
2731
2732                 /* existing SMB ses has a server reference already */
2733                 cifs_put_tcp_session(server, 0);
2734                 free_xid(xid);
2735                 return ses;
2736         }
2737
2738         rc = -ENOMEM;
2739
2740         cifs_dbg(FYI, "Existing smb sess not found\n");
2741         ses = sesInfoAlloc();
2742         if (ses == NULL)
2743                 goto get_ses_fail;
2744
2745         /* new SMB session uses our server ref */
2746         ses->server = server;
2747         if (server->dstaddr.ss_family == AF_INET6)
2748                 sprintf(ses->serverName, "%pI6", &addr6->sin6_addr);
2749         else
2750                 sprintf(ses->serverName, "%pI4", &addr->sin_addr);
2751
2752         if (volume_info->username) {
2753                 ses->user_name = kstrdup(volume_info->username, GFP_KERNEL);
2754                 if (!ses->user_name)
2755                         goto get_ses_fail;
2756         }
2757
2758         /* volume_info->password freed at unmount */
2759         if (volume_info->password) {
2760                 ses->password = kstrdup(volume_info->password, GFP_KERNEL);
2761                 if (!ses->password)
2762                         goto get_ses_fail;
2763         }
2764         if (volume_info->domainname) {
2765                 ses->domainName = kstrdup(volume_info->domainname, GFP_KERNEL);
2766                 if (!ses->domainName)
2767                         goto get_ses_fail;
2768         }
2769         if (volume_info->domainauto)
2770                 ses->domainAuto = volume_info->domainauto;
2771         ses->cred_uid = volume_info->cred_uid;
2772         ses->linux_uid = volume_info->linux_uid;
2773
2774         ses->sectype = volume_info->sectype;
2775         ses->sign = volume_info->sign;
2776
2777         mutex_lock(&ses->session_mutex);
2778         rc = cifs_negotiate_protocol(xid, ses);
2779         if (!rc)
2780                 rc = cifs_setup_session(xid, ses, volume_info->local_nls);
2781         mutex_unlock(&ses->session_mutex);
2782         if (rc)
2783                 goto get_ses_fail;
2784
2785         /* success, put it on the list */
2786         spin_lock(&cifs_tcp_ses_lock);
2787         list_add(&ses->smb_ses_list, &server->smb_ses_list);
2788         spin_unlock(&cifs_tcp_ses_lock);
2789
2790         free_xid(xid);
2791         return ses;
2792
2793 get_ses_fail:
2794         sesInfoFree(ses);
2795         free_xid(xid);
2796         return ERR_PTR(rc);
2797 }
2798
2799 static int match_tcon(struct cifs_tcon *tcon, struct smb_vol *volume_info)
2800 {
2801         if (tcon->tidStatus == CifsExiting)
2802                 return 0;
2803         if (strncmp(tcon->treeName, volume_info->UNC, MAX_TREE_SIZE))
2804                 return 0;
2805         if (tcon->seal != volume_info->seal)
2806                 return 0;
2807         if (tcon->snapshot_time != volume_info->snapshot_time)
2808                 return 0;
2809         return 1;
2810 }
2811
2812 static struct cifs_tcon *
2813 cifs_find_tcon(struct cifs_ses *ses, struct smb_vol *volume_info)
2814 {
2815         struct list_head *tmp;
2816         struct cifs_tcon *tcon;
2817
2818         spin_lock(&cifs_tcp_ses_lock);
2819         list_for_each(tmp, &ses->tcon_list) {
2820                 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
2821                 if (!match_tcon(tcon, volume_info))
2822                         continue;
2823                 ++tcon->tc_count;
2824                 spin_unlock(&cifs_tcp_ses_lock);
2825                 return tcon;
2826         }
2827         spin_unlock(&cifs_tcp_ses_lock);
2828         return NULL;
2829 }
2830
2831 void
2832 cifs_put_tcon(struct cifs_tcon *tcon)
2833 {
2834         unsigned int xid;
2835         struct cifs_ses *ses = tcon->ses;
2836
2837         cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2838         spin_lock(&cifs_tcp_ses_lock);
2839         if (--tcon->tc_count > 0) {
2840                 spin_unlock(&cifs_tcp_ses_lock);
2841                 return;
2842         }
2843
2844         list_del_init(&tcon->tcon_list);
2845         spin_unlock(&cifs_tcp_ses_lock);
2846
2847         xid = get_xid();
2848         if (ses->server->ops->tree_disconnect)
2849                 ses->server->ops->tree_disconnect(xid, tcon);
2850         _free_xid(xid);
2851
2852         cifs_fscache_release_super_cookie(tcon);
2853         tconInfoFree(tcon);
2854         cifs_put_smb_ses(ses);
2855 }
2856
2857 static struct cifs_tcon *
2858 cifs_get_tcon(struct cifs_ses *ses, struct smb_vol *volume_info)
2859 {
2860         int rc, xid;
2861         struct cifs_tcon *tcon;
2862
2863         tcon = cifs_find_tcon(ses, volume_info);
2864         if (tcon) {
2865                 cifs_dbg(FYI, "Found match on UNC path\n");
2866                 /* existing tcon already has a reference */
2867                 cifs_put_smb_ses(ses);
2868                 return tcon;
2869         }
2870
2871         if (!ses->server->ops->tree_connect) {
2872                 rc = -ENOSYS;
2873                 goto out_fail;
2874         }
2875
2876         tcon = tconInfoAlloc();
2877         if (tcon == NULL) {
2878                 rc = -ENOMEM;
2879                 goto out_fail;
2880         }
2881
2882         if (volume_info->snapshot_time) {
2883                 if (ses->server->vals->protocol_id == 0) {
2884                         cifs_dbg(VFS,
2885                              "Use SMB2 or later for snapshot mount option\n");
2886                         rc = -EOPNOTSUPP;
2887                         goto out_fail;
2888                 } else
2889                         tcon->snapshot_time = volume_info->snapshot_time;
2890         }
2891
2892         tcon->ses = ses;
2893         if (volume_info->password) {
2894                 tcon->password = kstrdup(volume_info->password, GFP_KERNEL);
2895                 if (!tcon->password) {
2896                         rc = -ENOMEM;
2897                         goto out_fail;
2898                 }
2899         }
2900
2901         /*
2902          * BB Do we need to wrap session_mutex around this TCon call and Unix
2903          * SetFS as we do on SessSetup and reconnect?
2904          */
2905         xid = get_xid();
2906         rc = ses->server->ops->tree_connect(xid, ses, volume_info->UNC, tcon,
2907                                             volume_info->local_nls);
2908         free_xid(xid);
2909         cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2910         if (rc)
2911                 goto out_fail;
2912
2913         if (volume_info->nodfs) {
2914                 tcon->Flags &= ~SMB_SHARE_IS_IN_DFS;
2915                 cifs_dbg(FYI, "DFS disabled (%d)\n", tcon->Flags);
2916         }
2917         tcon->use_persistent = false;
2918         /* check if SMB2 or later, CIFS does not support persistent handles */
2919         if (volume_info->persistent) {
2920                 if (ses->server->vals->protocol_id == 0) {
2921                         cifs_dbg(VFS,
2922                              "SMB3 or later required for persistent handles\n");
2923                         rc = -EOPNOTSUPP;
2924                         goto out_fail;
2925                 } else if (ses->server->capabilities &
2926                            SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2927                         tcon->use_persistent = true;
2928                 else /* persistent handles requested but not supported */ {
2929                         cifs_dbg(VFS,
2930                                 "Persistent handles not supported on share\n");
2931                         rc = -EOPNOTSUPP;
2932                         goto out_fail;
2933                 }
2934         } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2935              && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2936              && (volume_info->nopersistent == false)) {
2937                 cifs_dbg(FYI, "enabling persistent handles\n");
2938                 tcon->use_persistent = true;
2939         } else if (volume_info->resilient) {
2940                 if (ses->server->vals->protocol_id == 0) {
2941                         cifs_dbg(VFS,
2942                              "SMB2.1 or later required for resilient handles\n");
2943                         rc = -EOPNOTSUPP;
2944                         goto out_fail;
2945                 }
2946                 tcon->use_resilient = true;
2947         }
2948
2949         if (volume_info->seal) {
2950                 if (ses->server->vals->protocol_id == 0) {
2951                         cifs_dbg(VFS,
2952                                  "SMB3 or later required for encryption\n");
2953                         rc = -EOPNOTSUPP;
2954                         goto out_fail;
2955                 } else if (tcon->ses->server->capabilities &
2956                                         SMB2_GLOBAL_CAP_ENCRYPTION)
2957                         tcon->seal = true;
2958                 else {
2959                         cifs_dbg(VFS, "Encryption is not supported on share\n");
2960                         rc = -EOPNOTSUPP;
2961                         goto out_fail;
2962                 }
2963         }
2964
2965         /*
2966          * We can have only one retry value for a connection to a share so for
2967          * resources mounted more than once to the same server share the last
2968          * value passed in for the retry flag is used.
2969          */
2970         tcon->retry = volume_info->retry;
2971         tcon->nocase = volume_info->nocase;
2972         tcon->local_lease = volume_info->local_lease;
2973         INIT_LIST_HEAD(&tcon->pending_opens);
2974
2975         spin_lock(&cifs_tcp_ses_lock);
2976         list_add(&tcon->tcon_list, &ses->tcon_list);
2977         spin_unlock(&cifs_tcp_ses_lock);
2978
2979         cifs_fscache_get_super_cookie(tcon);
2980
2981         return tcon;
2982
2983 out_fail:
2984         tconInfoFree(tcon);
2985         return ERR_PTR(rc);
2986 }
2987
2988 void
2989 cifs_put_tlink(struct tcon_link *tlink)
2990 {
2991         if (!tlink || IS_ERR(tlink))
2992                 return;
2993
2994         if (!atomic_dec_and_test(&tlink->tl_count) ||
2995             test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2996                 tlink->tl_time = jiffies;
2997                 return;
2998         }
2999
3000         if (!IS_ERR(tlink_tcon(tlink)))
3001                 cifs_put_tcon(tlink_tcon(tlink));
3002         kfree(tlink);
3003         return;
3004 }
3005
3006 static inline struct tcon_link *
3007 cifs_sb_master_tlink(struct cifs_sb_info *cifs_sb)
3008 {
3009         return cifs_sb->master_tlink;
3010 }
3011
3012 static int
3013 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
3014 {
3015         struct cifs_sb_info *old = CIFS_SB(sb);
3016         struct cifs_sb_info *new = mnt_data->cifs_sb;
3017
3018         if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
3019                 return 0;
3020
3021         if ((old->mnt_cifs_flags & CIFS_MOUNT_MASK) !=
3022             (new->mnt_cifs_flags & CIFS_MOUNT_MASK))
3023                 return 0;
3024
3025         /*
3026          * We want to share sb only if we don't specify an r/wsize or
3027          * specified r/wsize is greater than or equal to existing one.
3028          */
3029         if (new->wsize && new->wsize < old->wsize)
3030                 return 0;
3031
3032         if (new->rsize && new->rsize < old->rsize)
3033                 return 0;
3034
3035         if (!uid_eq(old->mnt_uid, new->mnt_uid) || !gid_eq(old->mnt_gid, new->mnt_gid))
3036                 return 0;
3037
3038         if (old->mnt_file_mode != new->mnt_file_mode ||
3039             old->mnt_dir_mode != new->mnt_dir_mode)
3040                 return 0;
3041
3042         if (strcmp(old->local_nls->charset, new->local_nls->charset))
3043                 return 0;
3044
3045         if (old->actimeo != new->actimeo)
3046                 return 0;
3047
3048         return 1;
3049 }
3050
3051 static int
3052 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
3053 {
3054         struct cifs_sb_info *old = CIFS_SB(sb);
3055         struct cifs_sb_info *new = mnt_data->cifs_sb;
3056         bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
3057                 old->prepath;
3058         bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
3059                 new->prepath;
3060
3061         if (old_set && new_set && !strcmp(new->prepath, old->prepath))
3062                 return 1;
3063         else if (!old_set && !new_set)
3064                 return 1;
3065
3066         return 0;
3067 }
3068
3069 int
3070 cifs_match_super(struct super_block *sb, void *data)
3071 {
3072         struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
3073         struct smb_vol *volume_info;
3074         struct cifs_sb_info *cifs_sb;
3075         struct TCP_Server_Info *tcp_srv;
3076         struct cifs_ses *ses;
3077         struct cifs_tcon *tcon;
3078         struct tcon_link *tlink;
3079         int rc = 0;
3080
3081         spin_lock(&cifs_tcp_ses_lock);
3082         cifs_sb = CIFS_SB(sb);
3083         tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
3084         if (tlink == NULL) {
3085                 /* can not match superblock if tlink were ever null */
3086                 spin_unlock(&cifs_tcp_ses_lock);
3087                 return 0;
3088         }
3089         tcon = tlink_tcon(tlink);
3090         ses = tcon->ses;
3091         tcp_srv = ses->server;
3092
3093         volume_info = mnt_data->vol;
3094
3095         if (!match_server(tcp_srv, volume_info) ||
3096             !match_session(ses, volume_info) ||
3097             !match_tcon(tcon, volume_info) ||
3098             !match_prepath(sb, mnt_data)) {
3099                 rc = 0;
3100                 goto out;
3101         }
3102
3103         rc = compare_mount_options(sb, mnt_data);
3104 out:
3105         spin_unlock(&cifs_tcp_ses_lock);
3106         cifs_put_tlink(tlink);
3107         return rc;
3108 }
3109
3110 int
3111 get_dfs_path(const unsigned int xid, struct cifs_ses *ses, const char *old_path,
3112              const struct nls_table *nls_codepage, unsigned int *num_referrals,
3113              struct dfs_info3_param **referrals, int remap)
3114 {
3115         char *temp_unc;
3116         int rc = 0;
3117
3118         if (!ses->server->ops->tree_connect || !ses->server->ops->get_dfs_refer)
3119                 return -ENOSYS;
3120
3121         *num_referrals = 0;
3122         *referrals = NULL;
3123
3124         if (ses->ipc_tid == 0) {
3125                 temp_unc = kmalloc(2 /* for slashes */ +
3126                         strnlen(ses->serverName, SERVER_NAME_LEN_WITH_NULL * 2)
3127                                 + 1 + 4 /* slash IPC$ */ + 2, GFP_KERNEL);
3128                 if (temp_unc == NULL)
3129                         return -ENOMEM;
3130                 temp_unc[0] = '\\';
3131                 temp_unc[1] = '\\';
3132                 strcpy(temp_unc + 2, ses->serverName);
3133                 strcpy(temp_unc + 2 + strlen(ses->serverName), "\\IPC$");
3134                 rc = ses->server->ops->tree_connect(xid, ses, temp_unc, NULL,
3135                                                     nls_codepage);
3136                 cifs_dbg(FYI, "Tcon rc = %d ipc_tid = %d\n", rc, ses->ipc_tid);
3137                 kfree(temp_unc);
3138         }
3139         if (rc == 0)
3140                 rc = ses->server->ops->get_dfs_refer(xid, ses, old_path,
3141                                                      referrals, num_referrals,
3142                                                      nls_codepage, remap);
3143         /*
3144          * BB - map targetUNCs to dfs_info3 structures, here or in
3145          * ses->server->ops->get_dfs_refer.
3146          */
3147
3148         return rc;
3149 }
3150
3151 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3152 static struct lock_class_key cifs_key[2];
3153 static struct lock_class_key cifs_slock_key[2];
3154
3155 static inline void
3156 cifs_reclassify_socket4(struct socket *sock)
3157 {
3158         struct sock *sk = sock->sk;
3159         BUG_ON(!sock_allow_reclassification(sk));
3160         sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
3161                 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
3162 }
3163
3164 static inline void
3165 cifs_reclassify_socket6(struct socket *sock)
3166 {
3167         struct sock *sk = sock->sk;
3168         BUG_ON(!sock_allow_reclassification(sk));
3169         sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
3170                 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
3171 }
3172 #else
3173 static inline void
3174 cifs_reclassify_socket4(struct socket *sock)
3175 {
3176 }
3177
3178 static inline void
3179 cifs_reclassify_socket6(struct socket *sock)
3180 {
3181 }
3182 #endif
3183
3184 /* See RFC1001 section 14 on representation of Netbios names */
3185 static void rfc1002mangle(char *target, char *source, unsigned int length)
3186 {
3187         unsigned int i, j;
3188
3189         for (i = 0, j = 0; i < (length); i++) {
3190                 /* mask a nibble at a time and encode */
3191                 target[j] = 'A' + (0x0F & (source[i] >> 4));
3192                 target[j+1] = 'A' + (0x0F & source[i]);
3193                 j += 2;
3194         }
3195
3196 }
3197
3198 static int
3199 bind_socket(struct TCP_Server_Info *server)
3200 {
3201         int rc = 0;
3202         if (server->srcaddr.ss_family != AF_UNSPEC) {
3203                 /* Bind to the specified local IP address */
3204                 struct socket *socket = server->ssocket;
3205                 rc = socket->ops->bind(socket,
3206                                        (struct sockaddr *) &server->srcaddr,
3207                                        sizeof(server->srcaddr));
3208                 if (rc < 0) {
3209                         struct sockaddr_in *saddr4;
3210                         struct sockaddr_in6 *saddr6;
3211                         saddr4 = (struct sockaddr_in *)&server->srcaddr;
3212                         saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
3213                         if (saddr6->sin6_family == AF_INET6)
3214                                 cifs_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
3215                                          &saddr6->sin6_addr, rc);
3216                         else
3217                                 cifs_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
3218                                          &saddr4->sin_addr.s_addr, rc);
3219                 }
3220         }
3221         return rc;
3222 }
3223
3224 static int
3225 ip_rfc1001_connect(struct TCP_Server_Info *server)
3226 {
3227         int rc = 0;
3228         /*
3229          * some servers require RFC1001 sessinit before sending
3230          * negprot - BB check reconnection in case where second
3231          * sessinit is sent but no second negprot
3232          */
3233         struct rfc1002_session_packet *ses_init_buf;
3234         struct smb_hdr *smb_buf;
3235         ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
3236                                GFP_KERNEL);
3237         if (ses_init_buf) {
3238                 ses_init_buf->trailer.session_req.called_len = 32;
3239
3240                 if (server->server_RFC1001_name[0] != 0)
3241                         rfc1002mangle(ses_init_buf->trailer.
3242                                       session_req.called_name,
3243                                       server->server_RFC1001_name,
3244                                       RFC1001_NAME_LEN_WITH_NULL);
3245                 else
3246                         rfc1002mangle(ses_init_buf->trailer.
3247                                       session_req.called_name,
3248                                       DEFAULT_CIFS_CALLED_NAME,
3249                                       RFC1001_NAME_LEN_WITH_NULL);
3250
3251                 ses_init_buf->trailer.session_req.calling_len = 32;
3252
3253                 /*
3254                  * calling name ends in null (byte 16) from old smb
3255                  * convention.
3256                  */
3257                 if (server->workstation_RFC1001_name[0] != 0)
3258                         rfc1002mangle(ses_init_buf->trailer.
3259                                       session_req.calling_name,
3260                                       server->workstation_RFC1001_name,
3261                                       RFC1001_NAME_LEN_WITH_NULL);
3262                 else
3263                         rfc1002mangle(ses_init_buf->trailer.
3264                                       session_req.calling_name,
3265                                       "LINUX_CIFS_CLNT",
3266                                       RFC1001_NAME_LEN_WITH_NULL);
3267
3268                 ses_init_buf->trailer.session_req.scope1 = 0;
3269                 ses_init_buf->trailer.session_req.scope2 = 0;
3270                 smb_buf = (struct smb_hdr *)ses_init_buf;
3271
3272                 /* sizeof RFC1002_SESSION_REQUEST with no scope */
3273                 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
3274                 rc = smb_send(server, smb_buf, 0x44);
3275                 kfree(ses_init_buf);
3276                 /*
3277                  * RFC1001 layer in at least one server
3278                  * requires very short break before negprot
3279                  * presumably because not expecting negprot
3280                  * to follow so fast.  This is a simple
3281                  * solution that works without
3282                  * complicating the code and causes no
3283                  * significant slowing down on mount
3284                  * for everyone else
3285                  */
3286                 usleep_range(1000, 2000);
3287         }
3288         /*
3289          * else the negprot may still work without this
3290          * even though malloc failed
3291          */
3292
3293         return rc;
3294 }
3295
3296 static int
3297 generic_ip_connect(struct TCP_Server_Info *server)
3298 {
3299         int rc = 0;
3300         __be16 sport;
3301         int slen, sfamily;
3302         struct socket *socket = server->ssocket;
3303         struct sockaddr *saddr;
3304
3305         saddr = (struct sockaddr *) &server->dstaddr;
3306
3307         if (server->dstaddr.ss_family == AF_INET6) {
3308                 sport = ((struct sockaddr_in6 *) saddr)->sin6_port;
3309                 slen = sizeof(struct sockaddr_in6);
3310                 sfamily = AF_INET6;
3311         } else {
3312                 sport = ((struct sockaddr_in *) saddr)->sin_port;
3313                 slen = sizeof(struct sockaddr_in);
3314                 sfamily = AF_INET;
3315         }
3316
3317         if (socket == NULL) {
3318                 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3319                                    IPPROTO_TCP, &socket, 1);
3320                 if (rc < 0) {
3321                         cifs_dbg(VFS, "Error %d creating socket\n", rc);
3322                         server->ssocket = NULL;
3323                         return rc;
3324                 }
3325
3326                 /* BB other socket options to set KEEPALIVE, NODELAY? */
3327                 cifs_dbg(FYI, "Socket created\n");
3328                 server->ssocket = socket;
3329                 socket->sk->sk_allocation = GFP_NOFS;
3330                 if (sfamily == AF_INET6)
3331                         cifs_reclassify_socket6(socket);
3332                 else
3333                         cifs_reclassify_socket4(socket);
3334         }
3335
3336         rc = bind_socket(server);
3337         if (rc < 0)
3338                 return rc;
3339
3340         /*
3341          * Eventually check for other socket options to change from
3342          * the default. sock_setsockopt not used because it expects
3343          * user space buffer
3344          */
3345         socket->sk->sk_rcvtimeo = 7 * HZ;
3346         socket->sk->sk_sndtimeo = 5 * HZ;
3347
3348         /* make the bufsizes depend on wsize/rsize and max requests */
3349         if (server->noautotune) {
3350                 if (socket->sk->sk_sndbuf < (200 * 1024))
3351                         socket->sk->sk_sndbuf = 200 * 1024;
3352                 if (socket->sk->sk_rcvbuf < (140 * 1024))
3353                         socket->sk->sk_rcvbuf = 140 * 1024;
3354         }
3355
3356         if (server->tcp_nodelay) {
3357                 int val = 1;
3358                 rc = kernel_setsockopt(socket, SOL_TCP, TCP_NODELAY,
3359                                 (char *)&val, sizeof(val));
3360                 if (rc)
3361                         cifs_dbg(FYI, "set TCP_NODELAY socket option error %d\n",
3362                                  rc);
3363         }
3364
3365         cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3366                  socket->sk->sk_sndbuf,
3367                  socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3368
3369         rc = socket->ops->connect(socket, saddr, slen, 0);
3370         if (rc < 0) {
3371                 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3372                 sock_release(socket);
3373                 server->ssocket = NULL;
3374                 return rc;
3375         }
3376
3377         if (sport == htons(RFC1001_PORT))
3378                 rc = ip_rfc1001_connect(server);
3379
3380         return rc;
3381 }
3382
3383 static int
3384 ip_connect(struct TCP_Server_Info *server)
3385 {
3386         __be16 *sport;
3387         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3388         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3389
3390         if (server->dstaddr.ss_family == AF_INET6)
3391                 sport = &addr6->sin6_port;
3392         else
3393                 sport = &addr->sin_port;
3394
3395         if (*sport == 0) {
3396                 int rc;
3397
3398                 /* try with 445 port at first */
3399                 *sport = htons(CIFS_PORT);
3400
3401                 rc = generic_ip_connect(server);
3402                 if (rc >= 0)
3403                         return rc;
3404
3405                 /* if it failed, try with 139 port */
3406                 *sport = htons(RFC1001_PORT);
3407         }
3408
3409         return generic_ip_connect(server);
3410 }
3411
3412 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3413                           struct cifs_sb_info *cifs_sb, struct smb_vol *vol_info)
3414 {
3415         /* if we are reconnecting then should we check to see if
3416          * any requested capabilities changed locally e.g. via
3417          * remount but we can not do much about it here
3418          * if they have (even if we could detect it by the following)
3419          * Perhaps we could add a backpointer to array of sb from tcon
3420          * or if we change to make all sb to same share the same
3421          * sb as NFS - then we only have one backpointer to sb.
3422          * What if we wanted to mount the server share twice once with
3423          * and once without posixacls or posix paths? */
3424         __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3425
3426         if (vol_info && vol_info->no_linux_ext) {
3427                 tcon->fsUnixInfo.Capability = 0;
3428                 tcon->unix_ext = 0; /* Unix Extensions disabled */
3429                 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3430                 return;
3431         } else if (vol_info)
3432                 tcon->unix_ext = 1; /* Unix Extensions supported */
3433
3434         if (tcon->unix_ext == 0) {
3435                 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3436                 return;
3437         }
3438
3439         if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3440                 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3441                 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3442                 /* check for reconnect case in which we do not
3443                    want to change the mount behavior if we can avoid it */
3444                 if (vol_info == NULL) {
3445                         /* turn off POSIX ACL and PATHNAMES if not set
3446                            originally at mount time */
3447                         if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3448                                 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3449                         if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3450                                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3451                                         cifs_dbg(VFS, "POSIXPATH support change\n");
3452                                 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3453                         } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3454                                 cifs_dbg(VFS, "possible reconnect error\n");
3455                                 cifs_dbg(VFS, "server disabled POSIX path support\n");
3456                         }
3457                 }
3458
3459                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3460                         cifs_dbg(VFS, "per-share encryption not supported yet\n");
3461
3462                 cap &= CIFS_UNIX_CAP_MASK;
3463                 if (vol_info && vol_info->no_psx_acl)
3464                         cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3465                 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3466                         cifs_dbg(FYI, "negotiated posix acl support\n");
3467                         if (cifs_sb)
3468                                 cifs_sb->mnt_cifs_flags |=
3469                                         CIFS_MOUNT_POSIXACL;
3470                 }
3471
3472                 if (vol_info && vol_info->posix_paths == 0)
3473                         cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3474                 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3475                         cifs_dbg(FYI, "negotiate posix pathnames\n");
3476                         if (cifs_sb)
3477                                 cifs_sb->mnt_cifs_flags |=
3478                                         CIFS_MOUNT_POSIX_PATHS;
3479                 }
3480
3481                 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3482 #ifdef CONFIG_CIFS_DEBUG2
3483                 if (cap & CIFS_UNIX_FCNTL_CAP)
3484                         cifs_dbg(FYI, "FCNTL cap\n");
3485                 if (cap & CIFS_UNIX_EXTATTR_CAP)
3486                         cifs_dbg(FYI, "EXTATTR cap\n");
3487                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3488                         cifs_dbg(FYI, "POSIX path cap\n");
3489                 if (cap & CIFS_UNIX_XATTR_CAP)
3490                         cifs_dbg(FYI, "XATTR cap\n");
3491                 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3492                         cifs_dbg(FYI, "POSIX ACL cap\n");
3493                 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3494                         cifs_dbg(FYI, "very large read cap\n");
3495                 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3496                         cifs_dbg(FYI, "very large write cap\n");
3497                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3498                         cifs_dbg(FYI, "transport encryption cap\n");
3499                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3500                         cifs_dbg(FYI, "mandatory transport encryption cap\n");
3501 #endif /* CIFS_DEBUG2 */
3502                 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3503                         if (vol_info == NULL) {
3504                                 cifs_dbg(FYI, "resetting capabilities failed\n");
3505                         } else
3506                                 cifs_dbg(VFS, "Negotiating Unix capabilities with the server failed. Consider mounting with the Unix Extensions disabled if problems are found by specifying the nounix mount option.\n");
3507
3508                 }
3509         }
3510 }
3511
3512 int cifs_setup_cifs_sb(struct smb_vol *pvolume_info,
3513                         struct cifs_sb_info *cifs_sb)
3514 {
3515         INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3516
3517         spin_lock_init(&cifs_sb->tlink_tree_lock);
3518         cifs_sb->tlink_tree = RB_ROOT;
3519
3520         /*
3521          * Temporarily set r/wsize for matching superblock. If we end up using
3522          * new sb then client will later negotiate it downward if needed.
3523          */
3524         cifs_sb->rsize = pvolume_info->rsize;
3525         cifs_sb->wsize = pvolume_info->wsize;
3526
3527         cifs_sb->mnt_uid = pvolume_info->linux_uid;
3528         cifs_sb->mnt_gid = pvolume_info->linux_gid;
3529         cifs_sb->mnt_file_mode = pvolume_info->file_mode;
3530         cifs_sb->mnt_dir_mode = pvolume_info->dir_mode;
3531         cifs_dbg(FYI, "file mode: %04ho  dir mode: %04ho\n",
3532                  cifs_sb->mnt_file_mode, cifs_sb->mnt_dir_mode);
3533
3534         cifs_sb->actimeo = pvolume_info->actimeo;
3535         cifs_sb->local_nls = pvolume_info->local_nls;
3536
3537         if (pvolume_info->noperm)
3538                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_PERM;
3539         if (pvolume_info->setuids)
3540                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SET_UID;
3541         if (pvolume_info->setuidfromacl)
3542                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UID_FROM_ACL;
3543         if (pvolume_info->server_ino)
3544                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SERVER_INUM;
3545         if (pvolume_info->remap)
3546                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SFM_CHR;
3547         if (pvolume_info->sfu_remap)
3548                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SPECIAL_CHR;
3549         if (pvolume_info->no_xattr)
3550                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_XATTR;
3551         if (pvolume_info->sfu_emul)
3552                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UNX_EMUL;
3553         if (pvolume_info->nobrl)
3554                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_BRL;
3555         if (pvolume_info->nostrictsync)
3556                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOSSYNC;
3557         if (pvolume_info->mand_lock)
3558                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOPOSIXBRL;
3559         if (pvolume_info->rwpidforward)
3560                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RWPIDFORWARD;
3561         if (pvolume_info->cifs_acl)
3562                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_ACL;
3563         if (pvolume_info->backupuid_specified) {
3564                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_BACKUPUID;
3565                 cifs_sb->mnt_backupuid = pvolume_info->backupuid;
3566         }
3567         if (pvolume_info->backupgid_specified) {
3568                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_BACKUPGID;
3569                 cifs_sb->mnt_backupgid = pvolume_info->backupgid;
3570         }
3571         if (pvolume_info->override_uid)
3572                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_UID;
3573         if (pvolume_info->override_gid)
3574                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_GID;
3575         if (pvolume_info->dynperm)
3576                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DYNPERM;
3577         if (pvolume_info->fsc)
3578                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_FSCACHE;
3579         if (pvolume_info->multiuser)
3580                 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_MULTIUSER |
3581                                             CIFS_MOUNT_NO_PERM);
3582         if (pvolume_info->strict_io)
3583                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_STRICT_IO;
3584         if (pvolume_info->direct_io) {
3585                 cifs_dbg(FYI, "mounting share using direct i/o\n");
3586                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DIRECT_IO;
3587         }
3588         if (pvolume_info->mfsymlinks) {
3589                 if (pvolume_info->sfu_emul) {
3590                         /*
3591                          * Our SFU ("Services for Unix" emulation does not allow
3592                          * creating symlinks but does allow reading existing SFU
3593                          * symlinks (it does allow both creating and reading SFU
3594                          * style mknod and FIFOs though). When "mfsymlinks" and
3595                          * "sfu" are both enabled at the same time, it allows
3596                          * reading both types of symlinks, but will only create
3597                          * them with mfsymlinks format. This allows better
3598                          * Apple compatibility (probably better for Samba too)
3599                          * while still recognizing old Windows style symlinks.
3600                          */
3601                         cifs_dbg(VFS, "mount options mfsymlinks and sfu both enabled\n");
3602                 }
3603                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MF_SYMLINKS;
3604         }
3605
3606         if ((pvolume_info->cifs_acl) && (pvolume_info->dynperm))
3607                 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3608
3609         if (pvolume_info->prepath) {
3610                 cifs_sb->prepath = kstrdup(pvolume_info->prepath, GFP_KERNEL);
3611                 if (cifs_sb->prepath == NULL)
3612                         return -ENOMEM;
3613         }
3614
3615         return 0;
3616 }
3617
3618 static void
3619 cleanup_volume_info_contents(struct smb_vol *volume_info)
3620 {
3621         kfree(volume_info->username);
3622         kzfree(volume_info->password);
3623         kfree(volume_info->UNC);
3624         kfree(volume_info->domainname);
3625         kfree(volume_info->iocharset);
3626         kfree(volume_info->prepath);
3627 }
3628
3629 void
3630 cifs_cleanup_volume_info(struct smb_vol *volume_info)
3631 {
3632         if (!volume_info)
3633                 return;
3634         cleanup_volume_info_contents(volume_info);
3635         kfree(volume_info);
3636 }
3637
3638
3639 #ifdef CONFIG_CIFS_DFS_UPCALL
3640 /*
3641  * cifs_build_path_to_root returns full path to root when we do not have an
3642  * exiting connection (tcon)
3643  */
3644 static char *
3645 build_unc_path_to_root(const struct smb_vol *vol,
3646                 const struct cifs_sb_info *cifs_sb)
3647 {
3648         char *full_path, *pos;
3649         unsigned int pplen = vol->prepath ? strlen(vol->prepath) + 1 : 0;
3650         unsigned int unc_len = strnlen(vol->UNC, MAX_TREE_SIZE + 1);
3651
3652         full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3653         if (full_path == NULL)
3654                 return ERR_PTR(-ENOMEM);
3655
3656         strncpy(full_path, vol->UNC, unc_len);
3657         pos = full_path + unc_len;
3658
3659         if (pplen) {
3660                 *pos = CIFS_DIR_SEP(cifs_sb);
3661                 strncpy(pos + 1, vol->prepath, pplen);
3662                 pos += pplen;
3663         }
3664
3665         *pos = '\0'; /* add trailing null */
3666         convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3667         cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3668         return full_path;
3669 }
3670
3671 /*
3672  * Perform a dfs referral query for a share and (optionally) prefix
3673  *
3674  * If a referral is found, cifs_sb->mountdata will be (re-)allocated
3675  * to a string containing updated options for the submount.  Otherwise it
3676  * will be left untouched.
3677  *
3678  * Returns the rc from get_dfs_path to the caller, which can be used to
3679  * determine whether there were referrals.
3680  */
3681 static int
3682 expand_dfs_referral(const unsigned int xid, struct cifs_ses *ses,
3683                     struct smb_vol *volume_info, struct cifs_sb_info *cifs_sb,
3684                     int check_prefix)
3685 {
3686         int rc;
3687         unsigned int num_referrals = 0;
3688         struct dfs_info3_param *referrals = NULL;
3689         char *full_path = NULL, *ref_path = NULL, *mdata = NULL;
3690
3691         full_path = build_unc_path_to_root(volume_info, cifs_sb);
3692         if (IS_ERR(full_path))
3693                 return PTR_ERR(full_path);
3694
3695         /* For DFS paths, skip the first '\' of the UNC */
3696         ref_path = check_prefix ? full_path + 1 : volume_info->UNC + 1;
3697
3698         rc = get_dfs_path(xid, ses, ref_path, cifs_sb->local_nls,
3699                           &num_referrals, &referrals, cifs_remap(cifs_sb));
3700
3701         if (!rc && num_referrals > 0) {
3702                 char *fake_devname = NULL;
3703
3704                 mdata = cifs_compose_mount_options(cifs_sb->mountdata,
3705                                                    full_path + 1, referrals,
3706                                                    &fake_devname);
3707
3708                 free_dfs_info_array(referrals, num_referrals);
3709
3710                 if (IS_ERR(mdata)) {
3711                         rc = PTR_ERR(mdata);
3712                         mdata = NULL;
3713                 } else {
3714                         cleanup_volume_info_contents(volume_info);
3715                         rc = cifs_setup_volume_info(volume_info, mdata,
3716                                                         fake_devname);
3717                 }
3718                 kfree(fake_devname);
3719                 kfree(cifs_sb->mountdata);
3720                 cifs_sb->mountdata = mdata;
3721         }
3722         kfree(full_path);
3723         return rc;
3724 }
3725 #endif
3726
3727 static int
3728 cifs_setup_volume_info(struct smb_vol *volume_info, char *mount_data,
3729                         const char *devname)
3730 {
3731         int rc = 0;
3732
3733         if (cifs_parse_mount_options(mount_data, devname, volume_info))
3734                 return -EINVAL;
3735
3736         if (volume_info->nullauth) {
3737                 cifs_dbg(FYI, "Anonymous login\n");
3738                 kfree(volume_info->username);
3739                 volume_info->username = NULL;
3740         } else if (volume_info->username) {
3741                 /* BB fixme parse for domain name here */
3742                 cifs_dbg(FYI, "Username: %s\n", volume_info->username);
3743         } else {
3744                 cifs_dbg(VFS, "No username specified\n");
3745         /* In userspace mount helper we can get user name from alternate
3746            locations such as env variables and files on disk */
3747                 return -EINVAL;
3748         }
3749
3750         /* this is needed for ASCII cp to Unicode converts */
3751         if (volume_info->iocharset == NULL) {
3752                 /* load_nls_default cannot return null */
3753                 volume_info->local_nls = load_nls_default();
3754         } else {
3755                 volume_info->local_nls = load_nls(volume_info->iocharset);
3756                 if (volume_info->local_nls == NULL) {
3757                         cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3758                                  volume_info->iocharset);
3759                         return -ELIBACC;
3760                 }
3761         }
3762
3763         return rc;
3764 }
3765
3766 struct smb_vol *
3767 cifs_get_volume_info(char *mount_data, const char *devname)
3768 {
3769         int rc;
3770         struct smb_vol *volume_info;
3771
3772         volume_info = kmalloc(sizeof(struct smb_vol), GFP_KERNEL);
3773         if (!volume_info)
3774                 return ERR_PTR(-ENOMEM);
3775
3776         rc = cifs_setup_volume_info(volume_info, mount_data, devname);
3777         if (rc) {
3778                 cifs_cleanup_volume_info(volume_info);
3779                 volume_info = ERR_PTR(rc);
3780         }
3781
3782         return volume_info;
3783 }
3784
3785 static int
3786 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3787                                         unsigned int xid,
3788                                         struct cifs_tcon *tcon,
3789                                         struct cifs_sb_info *cifs_sb,
3790                                         char *full_path)
3791 {
3792         int rc;
3793         char *s;
3794         char sep, tmp;
3795
3796         sep = CIFS_DIR_SEP(cifs_sb);
3797         s = full_path;
3798
3799         rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3800         while (rc == 0) {
3801                 /* skip separators */
3802                 while (*s == sep)
3803                         s++;
3804                 if (!*s)
3805                         break;
3806                 /* next separator */
3807                 while (*s && *s != sep)
3808                         s++;
3809
3810                 /*
3811                  * temporarily null-terminate the path at the end of
3812                  * the current component
3813                  */
3814                 tmp = *s;
3815                 *s = 0;
3816                 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3817                                                      full_path);
3818                 *s = tmp;
3819         }
3820         return rc;
3821 }
3822
3823 int
3824 cifs_mount(struct cifs_sb_info *cifs_sb, struct smb_vol *volume_info)
3825 {
3826         int rc;
3827         unsigned int xid;
3828         struct cifs_ses *ses;
3829         struct cifs_tcon *tcon;
3830         struct TCP_Server_Info *server;
3831         char   *full_path;
3832         struct tcon_link *tlink;
3833 #ifdef CONFIG_CIFS_DFS_UPCALL
3834         int referral_walks_count = 0;
3835 #endif
3836
3837 #ifdef CONFIG_CIFS_DFS_UPCALL
3838 try_mount_again:
3839         /* cleanup activities if we're chasing a referral */
3840         if (referral_walks_count) {
3841                 if (tcon)
3842                         cifs_put_tcon(tcon);
3843                 else if (ses)
3844                         cifs_put_smb_ses(ses);
3845
3846                 cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3847
3848                 free_xid(xid);
3849         }
3850 #endif
3851         rc = 0;
3852         tcon = NULL;
3853         ses = NULL;
3854         server = NULL;
3855         full_path = NULL;
3856         tlink = NULL;
3857
3858         xid = get_xid();
3859
3860         /* get a reference to a tcp session */
3861         server = cifs_get_tcp_session(volume_info);
3862         if (IS_ERR(server)) {
3863                 rc = PTR_ERR(server);
3864                 goto out;
3865         }
3866         if ((volume_info->max_credits < 20) ||
3867              (volume_info->max_credits > 60000))
3868                 server->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
3869         else
3870                 server->max_credits = volume_info->max_credits;
3871         /* get a reference to a SMB session */
3872         ses = cifs_get_smb_ses(server, volume_info);
3873         if (IS_ERR(ses)) {
3874                 rc = PTR_ERR(ses);
3875                 ses = NULL;
3876                 goto mount_fail_check;
3877         }
3878
3879         if ((volume_info->persistent == true) && ((ses->server->capabilities &
3880                 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES) == 0)) {
3881                 cifs_dbg(VFS, "persistent handles not supported by server\n");
3882                 rc = -EOPNOTSUPP;
3883                 goto mount_fail_check;
3884         }
3885
3886         /* search for existing tcon to this server share */
3887         tcon = cifs_get_tcon(ses, volume_info);
3888         if (IS_ERR(tcon)) {
3889                 rc = PTR_ERR(tcon);
3890                 tcon = NULL;
3891                 if (rc == -EACCES)
3892                         goto mount_fail_check;
3893
3894                 goto remote_path_check;
3895         }
3896
3897         /* tell server which Unix caps we support */
3898         if (cap_unix(tcon->ses)) {
3899                 /* reset of caps checks mount to see if unix extensions
3900                    disabled for just this mount */
3901                 reset_cifs_unix_caps(xid, tcon, cifs_sb, volume_info);
3902                 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3903                     (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3904                      CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3905                         rc = -EACCES;
3906                         goto mount_fail_check;
3907                 }
3908         } else
3909                 tcon->unix_ext = 0; /* server does not support them */
3910
3911         /* do not care if a following call succeed - informational */
3912         if (!tcon->ipc && server->ops->qfs_tcon)
3913                 server->ops->qfs_tcon(xid, tcon);
3914
3915         cifs_sb->wsize = server->ops->negotiate_wsize(tcon, volume_info);
3916         cifs_sb->rsize = server->ops->negotiate_rsize(tcon, volume_info);
3917
3918 remote_path_check:
3919 #ifdef CONFIG_CIFS_DFS_UPCALL
3920         /*
3921          * Perform an unconditional check for whether there are DFS
3922          * referrals for this path without prefix, to provide support
3923          * for DFS referrals from w2k8 servers which don't seem to respond
3924          * with PATH_NOT_COVERED to requests that include the prefix.
3925          * Chase the referral if found, otherwise continue normally.
3926          */
3927         if (referral_walks_count == 0) {
3928                 int refrc = expand_dfs_referral(xid, ses, volume_info, cifs_sb,
3929                                                 false);
3930                 if (!refrc) {
3931                         referral_walks_count++;
3932                         goto try_mount_again;
3933                 }
3934         }
3935 #endif
3936
3937         /* check if a whole path is not remote */
3938         if (!rc && tcon) {
3939                 if (!server->ops->is_path_accessible) {
3940                         rc = -ENOSYS;
3941                         goto mount_fail_check;
3942                 }
3943                 /*
3944                  * cifs_build_path_to_root works only when we have a valid tcon
3945                  */
3946                 full_path = cifs_build_path_to_root(volume_info, cifs_sb, tcon,
3947                                         tcon->Flags & SMB_SHARE_IS_IN_DFS);
3948                 if (full_path == NULL) {
3949                         rc = -ENOMEM;
3950                         goto mount_fail_check;
3951                 }
3952                 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3953                                                      full_path);
3954                 if (rc != 0 && rc != -EREMOTE) {
3955                         kfree(full_path);
3956                         goto mount_fail_check;
3957                 }
3958
3959                 if (rc != -EREMOTE) {
3960                         rc = cifs_are_all_path_components_accessible(server,
3961                                                              xid, tcon, cifs_sb,
3962                                                              full_path);
3963                         if (rc != 0) {
3964                                 cifs_dbg(VFS, "cannot query dirs between root and final path, "
3965                                          "enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3966                                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3967                                 rc = 0;
3968                         }
3969                 }
3970                 kfree(full_path);
3971         }
3972
3973         /* get referral if needed */
3974         if (rc == -EREMOTE) {
3975 #ifdef CONFIG_CIFS_DFS_UPCALL
3976                 if (referral_walks_count > MAX_NESTED_LINKS) {
3977                         /*
3978                          * BB: when we implement proper loop detection,
3979                          *     we will remove this check. But now we need it
3980                          *     to prevent an indefinite loop if 'DFS tree' is
3981                          *     misconfigured (i.e. has loops).
3982                          */
3983                         rc = -ELOOP;
3984                         goto mount_fail_check;
3985                 }
3986
3987                 rc = expand_dfs_referral(xid, ses, volume_info, cifs_sb, true);
3988
3989                 if (!rc) {
3990                         referral_walks_count++;
3991                         goto try_mount_again;
3992                 }
3993                 goto mount_fail_check;
3994 #else /* No DFS support, return error on mount */
3995                 rc = -EOPNOTSUPP;
3996 #endif
3997         }
3998
3999         if (rc)
4000                 goto mount_fail_check;
4001
4002         /* now, hang the tcon off of the superblock */
4003         tlink = kzalloc(sizeof *tlink, GFP_KERNEL);
4004         if (tlink == NULL) {
4005                 rc = -ENOMEM;
4006                 goto mount_fail_check;
4007         }
4008
4009         tlink->tl_uid = ses->linux_uid;
4010         tlink->tl_tcon = tcon;
4011         tlink->tl_time = jiffies;
4012         set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
4013         set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4014
4015         cifs_sb->master_tlink = tlink;
4016         spin_lock(&cifs_sb->tlink_tree_lock);
4017         tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4018         spin_unlock(&cifs_sb->tlink_tree_lock);
4019
4020         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4021                                 TLINK_IDLE_EXPIRE);
4022
4023 mount_fail_check:
4024         /* on error free sesinfo and tcon struct if needed */
4025         if (rc) {
4026                 /* If find_unc succeeded then rc == 0 so we can not end */
4027                 /* up accidentally freeing someone elses tcon struct */
4028                 if (tcon)
4029                         cifs_put_tcon(tcon);
4030                 else if (ses)
4031                         cifs_put_smb_ses(ses);
4032                 else
4033                         cifs_put_tcp_session(server, 0);
4034         }
4035
4036 out:
4037         free_xid(xid);
4038         return rc;
4039 }
4040
4041 /*
4042  * Issue a TREE_CONNECT request. Note that for IPC$ shares, that the tcon
4043  * pointer may be NULL.
4044  */
4045 int
4046 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
4047          const char *tree, struct cifs_tcon *tcon,
4048          const struct nls_table *nls_codepage)
4049 {
4050         struct smb_hdr *smb_buffer;
4051         struct smb_hdr *smb_buffer_response;
4052         TCONX_REQ *pSMB;
4053         TCONX_RSP *pSMBr;
4054         unsigned char *bcc_ptr;
4055         int rc = 0;
4056         int length;
4057         __u16 bytes_left, count;
4058
4059         if (ses == NULL)
4060                 return -EIO;
4061
4062         smb_buffer = cifs_buf_get();
4063         if (smb_buffer == NULL)
4064                 return -ENOMEM;
4065
4066         smb_buffer_response = smb_buffer;
4067
4068         header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
4069                         NULL /*no tid */ , 4 /*wct */ );
4070
4071         smb_buffer->Mid = get_next_mid(ses->server);
4072         smb_buffer->Uid = ses->Suid;
4073         pSMB = (TCONX_REQ *) smb_buffer;
4074         pSMBr = (TCONX_RSP *) smb_buffer_response;
4075
4076         pSMB->AndXCommand = 0xFF;
4077         pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
4078         bcc_ptr = &pSMB->Password[0];
4079         if (!tcon || (ses->server->sec_mode & SECMODE_USER)) {
4080                 pSMB->PasswordLength = cpu_to_le16(1);  /* minimum */
4081                 *bcc_ptr = 0; /* password is null byte */
4082                 bcc_ptr++;              /* skip password */
4083                 /* already aligned so no need to do it below */
4084         } else {
4085                 pSMB->PasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE);
4086                 /* BB FIXME add code to fail this if NTLMv2 or Kerberos
4087                    specified as required (when that support is added to
4088                    the vfs in the future) as only NTLM or the much
4089                    weaker LANMAN (which we do not send by default) is accepted
4090                    by Samba (not sure whether other servers allow
4091                    NTLMv2 password here) */
4092 #ifdef CONFIG_CIFS_WEAK_PW_HASH
4093                 if ((global_secflags & CIFSSEC_MAY_LANMAN) &&
4094                     (ses->sectype == LANMAN))
4095                         calc_lanman_hash(tcon->password, ses->server->cryptkey,
4096                                          ses->server->sec_mode &
4097                                             SECMODE_PW_ENCRYPT ? true : false,
4098                                          bcc_ptr);
4099                 else
4100 #endif /* CIFS_WEAK_PW_HASH */
4101                 rc = SMBNTencrypt(tcon->password, ses->server->cryptkey,
4102                                         bcc_ptr, nls_codepage);
4103                 if (rc) {
4104                         cifs_dbg(FYI, "%s Can't generate NTLM rsp. Error: %d\n",
4105                                  __func__, rc);
4106                         cifs_buf_release(smb_buffer);
4107                         return rc;
4108                 }
4109
4110                 bcc_ptr += CIFS_AUTH_RESP_SIZE;
4111                 if (ses->capabilities & CAP_UNICODE) {
4112                         /* must align unicode strings */
4113                         *bcc_ptr = 0; /* null byte password */
4114                         bcc_ptr++;
4115                 }
4116         }
4117
4118         if (ses->server->sign)
4119                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
4120
4121         if (ses->capabilities & CAP_STATUS32) {
4122                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
4123         }
4124         if (ses->capabilities & CAP_DFS) {
4125                 smb_buffer->Flags2 |= SMBFLG2_DFS;
4126         }
4127         if (ses->capabilities & CAP_UNICODE) {
4128                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
4129                 length =
4130                     cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
4131                         6 /* max utf8 char length in bytes */ *
4132                         (/* server len*/ + 256 /* share len */), nls_codepage);
4133                 bcc_ptr += 2 * length;  /* convert num 16 bit words to bytes */
4134                 bcc_ptr += 2;   /* skip trailing null */
4135         } else {                /* ASCII */
4136                 strcpy(bcc_ptr, tree);
4137                 bcc_ptr += strlen(tree) + 1;
4138         }
4139         strcpy(bcc_ptr, "?????");
4140         bcc_ptr += strlen("?????");
4141         bcc_ptr += 1;
4142         count = bcc_ptr - &pSMB->Password[0];
4143         pSMB->hdr.smb_buf_length = cpu_to_be32(be32_to_cpu(
4144                                         pSMB->hdr.smb_buf_length) + count);
4145         pSMB->ByteCount = cpu_to_le16(count);
4146
4147         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
4148                          0);
4149
4150         /* above now done in SendReceive */
4151         if ((rc == 0) && (tcon != NULL)) {
4152                 bool is_unicode;
4153
4154                 tcon->tidStatus = CifsGood;
4155                 tcon->need_reconnect = false;
4156                 tcon->tid = smb_buffer_response->Tid;
4157                 bcc_ptr = pByteArea(smb_buffer_response);
4158                 bytes_left = get_bcc(smb_buffer_response);
4159                 length = strnlen(bcc_ptr, bytes_left - 2);
4160                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
4161                         is_unicode = true;
4162                 else
4163                         is_unicode = false;
4164
4165
4166                 /* skip service field (NB: this field is always ASCII) */
4167                 if (length == 3) {
4168                         if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
4169                             (bcc_ptr[2] == 'C')) {
4170                                 cifs_dbg(FYI, "IPC connection\n");
4171                                 tcon->ipc = 1;
4172                         }
4173                 } else if (length == 2) {
4174                         if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
4175                                 /* the most common case */
4176                                 cifs_dbg(FYI, "disk share connection\n");
4177                         }
4178                 }
4179                 bcc_ptr += length + 1;
4180                 bytes_left -= (length + 1);
4181                 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
4182
4183                 /* mostly informational -- no need to fail on error here */
4184                 kfree(tcon->nativeFileSystem);
4185                 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
4186                                                       bytes_left, is_unicode,
4187                                                       nls_codepage);
4188
4189                 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
4190
4191                 if ((smb_buffer_response->WordCount == 3) ||
4192                          (smb_buffer_response->WordCount == 7))
4193                         /* field is in same location */
4194                         tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
4195                 else
4196                         tcon->Flags = 0;
4197                 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
4198         } else if ((rc == 0) && tcon == NULL) {
4199                 /* all we need to save for IPC$ connection */
4200                 ses->ipc_tid = smb_buffer_response->Tid;
4201         }
4202
4203         cifs_buf_release(smb_buffer);
4204         return rc;
4205 }
4206
4207 static void delayed_free(struct rcu_head *p)
4208 {
4209         struct cifs_sb_info *sbi = container_of(p, struct cifs_sb_info, rcu);
4210         unload_nls(sbi->local_nls);
4211         kfree(sbi);
4212 }
4213
4214 void
4215 cifs_umount(struct cifs_sb_info *cifs_sb)
4216 {
4217         struct rb_root *root = &cifs_sb->tlink_tree;
4218         struct rb_node *node;
4219         struct tcon_link *tlink;
4220
4221         cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
4222
4223         spin_lock(&cifs_sb->tlink_tree_lock);
4224         while ((node = rb_first(root))) {
4225                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4226                 cifs_get_tlink(tlink);
4227                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4228                 rb_erase(node, root);
4229
4230                 spin_unlock(&cifs_sb->tlink_tree_lock);
4231                 cifs_put_tlink(tlink);
4232                 spin_lock(&cifs_sb->tlink_tree_lock);
4233         }
4234         spin_unlock(&cifs_sb->tlink_tree_lock);
4235
4236         kfree(cifs_sb->mountdata);
4237         kfree(cifs_sb->prepath);
4238         call_rcu(&cifs_sb->rcu, delayed_free);
4239 }
4240
4241 int
4242 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses)
4243 {
4244         int rc = 0;
4245         struct TCP_Server_Info *server = ses->server;
4246
4247         if (!server->ops->need_neg || !server->ops->negotiate)
4248                 return -ENOSYS;
4249
4250         /* only send once per connect */
4251         if (!server->ops->need_neg(server))
4252                 return 0;
4253
4254         set_credits(server, 1);
4255
4256         rc = server->ops->negotiate(xid, ses);
4257         if (rc == 0) {
4258                 spin_lock(&GlobalMid_Lock);
4259                 if (server->tcpStatus == CifsNeedNegotiate)
4260                         server->tcpStatus = CifsGood;
4261                 else
4262                         rc = -EHOSTDOWN;
4263                 spin_unlock(&GlobalMid_Lock);
4264         }
4265
4266         return rc;
4267 }
4268
4269 int
4270 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4271                    struct nls_table *nls_info)
4272 {
4273         int rc = -ENOSYS;
4274         struct TCP_Server_Info *server = ses->server;
4275
4276         ses->capabilities = server->capabilities;
4277         if (linuxExtEnabled == 0)
4278                 ses->capabilities &= (~server->vals->cap_unix);
4279
4280         cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4281                  server->sec_mode, server->capabilities, server->timeAdj);
4282
4283         if (ses->auth_key.response) {
4284                 cifs_dbg(VFS, "Free previous auth_key.response = %p\n",
4285                          ses->auth_key.response);
4286                 kfree(ses->auth_key.response);
4287                 ses->auth_key.response = NULL;
4288                 ses->auth_key.len = 0;
4289         }
4290
4291         if (server->ops->sess_setup)
4292                 rc = server->ops->sess_setup(xid, ses, nls_info);
4293
4294         if (rc)
4295                 cifs_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4296
4297         return rc;
4298 }
4299
4300 static int
4301 cifs_set_vol_auth(struct smb_vol *vol, struct cifs_ses *ses)
4302 {
4303         vol->sectype = ses->sectype;
4304
4305         /* krb5 is special, since we don't need username or pw */
4306         if (vol->sectype == Kerberos)
4307                 return 0;
4308
4309         return cifs_set_cifscreds(vol, ses);
4310 }
4311
4312 static struct cifs_tcon *
4313 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4314 {
4315         int rc;
4316         struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4317         struct cifs_ses *ses;
4318         struct cifs_tcon *tcon = NULL;
4319         struct smb_vol *vol_info;
4320
4321         vol_info = kzalloc(sizeof(*vol_info), GFP_KERNEL);
4322         if (vol_info == NULL)
4323                 return ERR_PTR(-ENOMEM);
4324
4325         vol_info->local_nls = cifs_sb->local_nls;
4326         vol_info->linux_uid = fsuid;
4327         vol_info->cred_uid = fsuid;
4328         vol_info->UNC = master_tcon->treeName;
4329         vol_info->retry = master_tcon->retry;
4330         vol_info->nocase = master_tcon->nocase;
4331         vol_info->local_lease = master_tcon->local_lease;
4332         vol_info->resilient = master_tcon->use_resilient;
4333         vol_info->persistent = master_tcon->use_persistent;
4334         vol_info->no_linux_ext = !master_tcon->unix_ext;
4335         vol_info->sectype = master_tcon->ses->sectype;
4336         vol_info->sign = master_tcon->ses->sign;
4337         vol_info->seal = master_tcon->seal;
4338
4339         rc = cifs_set_vol_auth(vol_info, master_tcon->ses);
4340         if (rc) {
4341                 tcon = ERR_PTR(rc);
4342                 goto out;
4343         }
4344
4345         /* get a reference for the same TCP session */
4346         spin_lock(&cifs_tcp_ses_lock);
4347         ++master_tcon->ses->server->srv_count;
4348         spin_unlock(&cifs_tcp_ses_lock);
4349
4350         ses = cifs_get_smb_ses(master_tcon->ses->server, vol_info);
4351         if (IS_ERR(ses)) {
4352                 tcon = (struct cifs_tcon *)ses;
4353                 cifs_put_tcp_session(master_tcon->ses->server, 0);
4354                 goto out;
4355         }
4356
4357         tcon = cifs_get_tcon(ses, vol_info);
4358         if (IS_ERR(tcon)) {
4359                 cifs_put_smb_ses(ses);
4360                 goto out;
4361         }
4362
4363         if (cap_unix(ses))
4364                 reset_cifs_unix_caps(0, tcon, NULL, vol_info);
4365 out:
4366         kfree(vol_info->username);
4367         kzfree(vol_info->password);
4368         kfree(vol_info);
4369
4370         return tcon;
4371 }
4372
4373 struct cifs_tcon *
4374 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4375 {
4376         return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4377 }
4378
4379 /* find and return a tlink with given uid */
4380 static struct tcon_link *
4381 tlink_rb_search(struct rb_root *root, kuid_t uid)
4382 {
4383         struct rb_node *node = root->rb_node;
4384         struct tcon_link *tlink;
4385
4386         while (node) {
4387                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4388
4389                 if (uid_gt(tlink->tl_uid, uid))
4390                         node = node->rb_left;
4391                 else if (uid_lt(tlink->tl_uid, uid))
4392                         node = node->rb_right;
4393                 else
4394                         return tlink;
4395         }
4396         return NULL;
4397 }
4398
4399 /* insert a tcon_link into the tree */
4400 static void
4401 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4402 {
4403         struct rb_node **new = &(root->rb_node), *parent = NULL;
4404         struct tcon_link *tlink;
4405
4406         while (*new) {
4407                 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4408                 parent = *new;
4409
4410                 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4411                         new = &((*new)->rb_left);
4412                 else
4413                         new = &((*new)->rb_right);
4414         }
4415
4416         rb_link_node(&new_tlink->tl_rbnode, parent, new);
4417         rb_insert_color(&new_tlink->tl_rbnode, root);
4418 }
4419
4420 /*
4421  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4422  * current task.
4423  *
4424  * If the superblock doesn't refer to a multiuser mount, then just return
4425  * the master tcon for the mount.
4426  *
4427  * First, search the rbtree for an existing tcon for this fsuid. If one
4428  * exists, then check to see if it's pending construction. If it is then wait
4429  * for construction to complete. Once it's no longer pending, check to see if
4430  * it failed and either return an error or retry construction, depending on
4431  * the timeout.
4432  *
4433  * If one doesn't exist then insert a new tcon_link struct into the tree and
4434  * try to construct a new one.
4435  */
4436 struct tcon_link *
4437 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4438 {
4439         int ret;
4440         kuid_t fsuid = current_fsuid();
4441         struct tcon_link *tlink, *newtlink;
4442
4443         if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4444                 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4445
4446         spin_lock(&cifs_sb->tlink_tree_lock);
4447         tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4448         if (tlink)
4449                 cifs_get_tlink(tlink);
4450         spin_unlock(&cifs_sb->tlink_tree_lock);
4451
4452         if (tlink == NULL) {
4453                 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4454                 if (newtlink == NULL)
4455                         return ERR_PTR(-ENOMEM);
4456                 newtlink->tl_uid = fsuid;
4457                 newtlink->tl_tcon = ERR_PTR(-EACCES);
4458                 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4459                 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4460                 cifs_get_tlink(newtlink);
4461
4462                 spin_lock(&cifs_sb->tlink_tree_lock);
4463                 /* was one inserted after previous search? */
4464                 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4465                 if (tlink) {
4466                         cifs_get_tlink(tlink);
4467                         spin_unlock(&cifs_sb->tlink_tree_lock);
4468                         kfree(newtlink);
4469                         goto wait_for_construction;
4470                 }
4471                 tlink = newtlink;
4472                 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4473                 spin_unlock(&cifs_sb->tlink_tree_lock);
4474         } else {
4475 wait_for_construction:
4476                 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4477                                   TASK_INTERRUPTIBLE);
4478                 if (ret) {
4479                         cifs_put_tlink(tlink);
4480                         return ERR_PTR(-ERESTARTSYS);
4481                 }
4482
4483                 /* if it's good, return it */
4484                 if (!IS_ERR(tlink->tl_tcon))
4485                         return tlink;
4486
4487                 /* return error if we tried this already recently */
4488                 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4489                         cifs_put_tlink(tlink);
4490                         return ERR_PTR(-EACCES);
4491                 }
4492
4493                 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4494                         goto wait_for_construction;
4495         }
4496
4497         tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4498         clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4499         wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4500
4501         if (IS_ERR(tlink->tl_tcon)) {
4502                 cifs_put_tlink(tlink);
4503                 return ERR_PTR(-EACCES);
4504         }
4505
4506         return tlink;
4507 }
4508
4509 /*
4510  * periodic workqueue job that scans tcon_tree for a superblock and closes
4511  * out tcons.
4512  */
4513 static void
4514 cifs_prune_tlinks(struct work_struct *work)
4515 {
4516         struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4517                                                     prune_tlinks.work);
4518         struct rb_root *root = &cifs_sb->tlink_tree;
4519         struct rb_node *node = rb_first(root);
4520         struct rb_node *tmp;
4521         struct tcon_link *tlink;
4522
4523         /*
4524          * Because we drop the spinlock in the loop in order to put the tlink
4525          * it's not guarded against removal of links from the tree. The only
4526          * places that remove entries from the tree are this function and
4527          * umounts. Because this function is non-reentrant and is canceled
4528          * before umount can proceed, this is safe.
4529          */
4530         spin_lock(&cifs_sb->tlink_tree_lock);
4531         node = rb_first(root);
4532         while (node != NULL) {
4533                 tmp = node;
4534                 node = rb_next(tmp);
4535                 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4536
4537                 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4538                     atomic_read(&tlink->tl_count) != 0 ||
4539                     time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4540                         continue;
4541
4542                 cifs_get_tlink(tlink);
4543                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4544                 rb_erase(tmp, root);
4545
4546                 spin_unlock(&cifs_sb->tlink_tree_lock);
4547                 cifs_put_tlink(tlink);
4548                 spin_lock(&cifs_sb->tlink_tree_lock);
4549         }
4550         spin_unlock(&cifs_sb->tlink_tree_lock);
4551
4552         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4553                                 TLINK_IDLE_EXPIRE);
4554 }