GNU Linux-libre 4.14.290-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 = -ENOMEM;
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         cifs_dbg(FYI, "Existing smb sess not found\n");
2739         ses = sesInfoAlloc();
2740         if (ses == NULL)
2741                 goto get_ses_fail;
2742
2743         /* new SMB session uses our server ref */
2744         ses->server = server;
2745         if (server->dstaddr.ss_family == AF_INET6)
2746                 sprintf(ses->serverName, "%pI6", &addr6->sin6_addr);
2747         else
2748                 sprintf(ses->serverName, "%pI4", &addr->sin_addr);
2749
2750         if (volume_info->username) {
2751                 ses->user_name = kstrdup(volume_info->username, GFP_KERNEL);
2752                 if (!ses->user_name)
2753                         goto get_ses_fail;
2754         }
2755
2756         /* volume_info->password freed at unmount */
2757         if (volume_info->password) {
2758                 ses->password = kstrdup(volume_info->password, GFP_KERNEL);
2759                 if (!ses->password)
2760                         goto get_ses_fail;
2761         }
2762         if (volume_info->domainname) {
2763                 ses->domainName = kstrdup(volume_info->domainname, GFP_KERNEL);
2764                 if (!ses->domainName)
2765                         goto get_ses_fail;
2766         }
2767         if (volume_info->domainauto)
2768                 ses->domainAuto = volume_info->domainauto;
2769         ses->cred_uid = volume_info->cred_uid;
2770         ses->linux_uid = volume_info->linux_uid;
2771
2772         ses->sectype = volume_info->sectype;
2773         ses->sign = volume_info->sign;
2774
2775         mutex_lock(&ses->session_mutex);
2776         rc = cifs_negotiate_protocol(xid, ses);
2777         if (!rc)
2778                 rc = cifs_setup_session(xid, ses, volume_info->local_nls);
2779         mutex_unlock(&ses->session_mutex);
2780         if (rc)
2781                 goto get_ses_fail;
2782
2783         /* success, put it on the list */
2784         spin_lock(&cifs_tcp_ses_lock);
2785         list_add(&ses->smb_ses_list, &server->smb_ses_list);
2786         spin_unlock(&cifs_tcp_ses_lock);
2787
2788         free_xid(xid);
2789         return ses;
2790
2791 get_ses_fail:
2792         sesInfoFree(ses);
2793         free_xid(xid);
2794         return ERR_PTR(rc);
2795 }
2796
2797 static int match_tcon(struct cifs_tcon *tcon, struct smb_vol *volume_info)
2798 {
2799         if (tcon->tidStatus == CifsExiting)
2800                 return 0;
2801         if (strncmp(tcon->treeName, volume_info->UNC, MAX_TREE_SIZE))
2802                 return 0;
2803         if (tcon->seal != volume_info->seal)
2804                 return 0;
2805         if (tcon->snapshot_time != volume_info->snapshot_time)
2806                 return 0;
2807         return 1;
2808 }
2809
2810 static struct cifs_tcon *
2811 cifs_find_tcon(struct cifs_ses *ses, struct smb_vol *volume_info)
2812 {
2813         struct list_head *tmp;
2814         struct cifs_tcon *tcon;
2815
2816         spin_lock(&cifs_tcp_ses_lock);
2817         list_for_each(tmp, &ses->tcon_list) {
2818                 tcon = list_entry(tmp, struct cifs_tcon, tcon_list);
2819                 if (!match_tcon(tcon, volume_info))
2820                         continue;
2821                 ++tcon->tc_count;
2822                 spin_unlock(&cifs_tcp_ses_lock);
2823                 return tcon;
2824         }
2825         spin_unlock(&cifs_tcp_ses_lock);
2826         return NULL;
2827 }
2828
2829 void
2830 cifs_put_tcon(struct cifs_tcon *tcon)
2831 {
2832         unsigned int xid;
2833         struct cifs_ses *ses = tcon->ses;
2834
2835         cifs_dbg(FYI, "%s: tc_count=%d\n", __func__, tcon->tc_count);
2836         spin_lock(&cifs_tcp_ses_lock);
2837         if (--tcon->tc_count > 0) {
2838                 spin_unlock(&cifs_tcp_ses_lock);
2839                 return;
2840         }
2841
2842         list_del_init(&tcon->tcon_list);
2843         spin_unlock(&cifs_tcp_ses_lock);
2844
2845         xid = get_xid();
2846         if (ses->server->ops->tree_disconnect)
2847                 ses->server->ops->tree_disconnect(xid, tcon);
2848         _free_xid(xid);
2849
2850         cifs_fscache_release_super_cookie(tcon);
2851         tconInfoFree(tcon);
2852         cifs_put_smb_ses(ses);
2853 }
2854
2855 static struct cifs_tcon *
2856 cifs_get_tcon(struct cifs_ses *ses, struct smb_vol *volume_info)
2857 {
2858         int rc, xid;
2859         struct cifs_tcon *tcon;
2860
2861         tcon = cifs_find_tcon(ses, volume_info);
2862         if (tcon) {
2863                 cifs_dbg(FYI, "Found match on UNC path\n");
2864                 /* existing tcon already has a reference */
2865                 cifs_put_smb_ses(ses);
2866                 return tcon;
2867         }
2868
2869         if (!ses->server->ops->tree_connect) {
2870                 rc = -ENOSYS;
2871                 goto out_fail;
2872         }
2873
2874         tcon = tconInfoAlloc();
2875         if (tcon == NULL) {
2876                 rc = -ENOMEM;
2877                 goto out_fail;
2878         }
2879
2880         if (volume_info->snapshot_time) {
2881                 if (ses->server->vals->protocol_id == 0) {
2882                         cifs_dbg(VFS,
2883                              "Use SMB2 or later for snapshot mount option\n");
2884                         rc = -EOPNOTSUPP;
2885                         goto out_fail;
2886                 } else
2887                         tcon->snapshot_time = volume_info->snapshot_time;
2888         }
2889
2890         tcon->ses = ses;
2891         if (volume_info->password) {
2892                 tcon->password = kstrdup(volume_info->password, GFP_KERNEL);
2893                 if (!tcon->password) {
2894                         rc = -ENOMEM;
2895                         goto out_fail;
2896                 }
2897         }
2898
2899         /*
2900          * BB Do we need to wrap session_mutex around this TCon call and Unix
2901          * SetFS as we do on SessSetup and reconnect?
2902          */
2903         xid = get_xid();
2904         rc = ses->server->ops->tree_connect(xid, ses, volume_info->UNC, tcon,
2905                                             volume_info->local_nls);
2906         free_xid(xid);
2907         cifs_dbg(FYI, "Tcon rc = %d\n", rc);
2908         if (rc)
2909                 goto out_fail;
2910
2911         if (volume_info->nodfs) {
2912                 tcon->Flags &= ~SMB_SHARE_IS_IN_DFS;
2913                 cifs_dbg(FYI, "DFS disabled (%d)\n", tcon->Flags);
2914         }
2915         tcon->use_persistent = false;
2916         /* check if SMB2 or later, CIFS does not support persistent handles */
2917         if (volume_info->persistent) {
2918                 if (ses->server->vals->protocol_id == 0) {
2919                         cifs_dbg(VFS,
2920                              "SMB3 or later required for persistent handles\n");
2921                         rc = -EOPNOTSUPP;
2922                         goto out_fail;
2923                 } else if (ses->server->capabilities &
2924                            SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2925                         tcon->use_persistent = true;
2926                 else /* persistent handles requested but not supported */ {
2927                         cifs_dbg(VFS,
2928                                 "Persistent handles not supported on share\n");
2929                         rc = -EOPNOTSUPP;
2930                         goto out_fail;
2931                 }
2932         } else if ((tcon->capabilities & SMB2_SHARE_CAP_CONTINUOUS_AVAILABILITY)
2933              && (ses->server->capabilities & SMB2_GLOBAL_CAP_PERSISTENT_HANDLES)
2934              && (volume_info->nopersistent == false)) {
2935                 cifs_dbg(FYI, "enabling persistent handles\n");
2936                 tcon->use_persistent = true;
2937         } else if (volume_info->resilient) {
2938                 if (ses->server->vals->protocol_id == 0) {
2939                         cifs_dbg(VFS,
2940                              "SMB2.1 or later required for resilient handles\n");
2941                         rc = -EOPNOTSUPP;
2942                         goto out_fail;
2943                 }
2944                 tcon->use_resilient = true;
2945         }
2946
2947         if (volume_info->seal) {
2948                 if (ses->server->vals->protocol_id == 0) {
2949                         cifs_dbg(VFS,
2950                                  "SMB3 or later required for encryption\n");
2951                         rc = -EOPNOTSUPP;
2952                         goto out_fail;
2953                 } else if (tcon->ses->server->capabilities &
2954                                         SMB2_GLOBAL_CAP_ENCRYPTION)
2955                         tcon->seal = true;
2956                 else {
2957                         cifs_dbg(VFS, "Encryption is not supported on share\n");
2958                         rc = -EOPNOTSUPP;
2959                         goto out_fail;
2960                 }
2961         }
2962
2963         /*
2964          * We can have only one retry value for a connection to a share so for
2965          * resources mounted more than once to the same server share the last
2966          * value passed in for the retry flag is used.
2967          */
2968         tcon->retry = volume_info->retry;
2969         tcon->nocase = volume_info->nocase;
2970         tcon->local_lease = volume_info->local_lease;
2971         INIT_LIST_HEAD(&tcon->pending_opens);
2972
2973         spin_lock(&cifs_tcp_ses_lock);
2974         list_add(&tcon->tcon_list, &ses->tcon_list);
2975         spin_unlock(&cifs_tcp_ses_lock);
2976
2977         cifs_fscache_get_super_cookie(tcon);
2978
2979         return tcon;
2980
2981 out_fail:
2982         tconInfoFree(tcon);
2983         return ERR_PTR(rc);
2984 }
2985
2986 void
2987 cifs_put_tlink(struct tcon_link *tlink)
2988 {
2989         if (!tlink || IS_ERR(tlink))
2990                 return;
2991
2992         if (!atomic_dec_and_test(&tlink->tl_count) ||
2993             test_bit(TCON_LINK_IN_TREE, &tlink->tl_flags)) {
2994                 tlink->tl_time = jiffies;
2995                 return;
2996         }
2997
2998         if (!IS_ERR(tlink_tcon(tlink)))
2999                 cifs_put_tcon(tlink_tcon(tlink));
3000         kfree(tlink);
3001         return;
3002 }
3003
3004 static inline struct tcon_link *
3005 cifs_sb_master_tlink(struct cifs_sb_info *cifs_sb)
3006 {
3007         return cifs_sb->master_tlink;
3008 }
3009
3010 static int
3011 compare_mount_options(struct super_block *sb, struct cifs_mnt_data *mnt_data)
3012 {
3013         struct cifs_sb_info *old = CIFS_SB(sb);
3014         struct cifs_sb_info *new = mnt_data->cifs_sb;
3015
3016         if ((sb->s_flags & CIFS_MS_MASK) != (mnt_data->flags & CIFS_MS_MASK))
3017                 return 0;
3018
3019         if ((old->mnt_cifs_flags & CIFS_MOUNT_MASK) !=
3020             (new->mnt_cifs_flags & CIFS_MOUNT_MASK))
3021                 return 0;
3022
3023         /*
3024          * We want to share sb only if we don't specify an r/wsize or
3025          * specified r/wsize is greater than or equal to existing one.
3026          */
3027         if (new->wsize && new->wsize < old->wsize)
3028                 return 0;
3029
3030         if (new->rsize && new->rsize < old->rsize)
3031                 return 0;
3032
3033         if (!uid_eq(old->mnt_uid, new->mnt_uid) || !gid_eq(old->mnt_gid, new->mnt_gid))
3034                 return 0;
3035
3036         if (old->mnt_file_mode != new->mnt_file_mode ||
3037             old->mnt_dir_mode != new->mnt_dir_mode)
3038                 return 0;
3039
3040         if (strcmp(old->local_nls->charset, new->local_nls->charset))
3041                 return 0;
3042
3043         if (old->actimeo != new->actimeo)
3044                 return 0;
3045
3046         return 1;
3047 }
3048
3049 static int
3050 match_prepath(struct super_block *sb, struct cifs_mnt_data *mnt_data)
3051 {
3052         struct cifs_sb_info *old = CIFS_SB(sb);
3053         struct cifs_sb_info *new = mnt_data->cifs_sb;
3054         bool old_set = (old->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
3055                 old->prepath;
3056         bool new_set = (new->mnt_cifs_flags & CIFS_MOUNT_USE_PREFIX_PATH) &&
3057                 new->prepath;
3058
3059         if (old_set && new_set && !strcmp(new->prepath, old->prepath))
3060                 return 1;
3061         else if (!old_set && !new_set)
3062                 return 1;
3063
3064         return 0;
3065 }
3066
3067 int
3068 cifs_match_super(struct super_block *sb, void *data)
3069 {
3070         struct cifs_mnt_data *mnt_data = (struct cifs_mnt_data *)data;
3071         struct smb_vol *volume_info;
3072         struct cifs_sb_info *cifs_sb;
3073         struct TCP_Server_Info *tcp_srv;
3074         struct cifs_ses *ses;
3075         struct cifs_tcon *tcon;
3076         struct tcon_link *tlink;
3077         int rc = 0;
3078
3079         spin_lock(&cifs_tcp_ses_lock);
3080         cifs_sb = CIFS_SB(sb);
3081         tlink = cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
3082         if (tlink == NULL) {
3083                 /* can not match superblock if tlink were ever null */
3084                 spin_unlock(&cifs_tcp_ses_lock);
3085                 return 0;
3086         }
3087         tcon = tlink_tcon(tlink);
3088         ses = tcon->ses;
3089         tcp_srv = ses->server;
3090
3091         volume_info = mnt_data->vol;
3092
3093         if (!match_server(tcp_srv, volume_info) ||
3094             !match_session(ses, volume_info) ||
3095             !match_tcon(tcon, volume_info) ||
3096             !match_prepath(sb, mnt_data)) {
3097                 rc = 0;
3098                 goto out;
3099         }
3100
3101         rc = compare_mount_options(sb, mnt_data);
3102 out:
3103         spin_unlock(&cifs_tcp_ses_lock);
3104         cifs_put_tlink(tlink);
3105         return rc;
3106 }
3107
3108 int
3109 get_dfs_path(const unsigned int xid, struct cifs_ses *ses, const char *old_path,
3110              const struct nls_table *nls_codepage, unsigned int *num_referrals,
3111              struct dfs_info3_param **referrals, int remap)
3112 {
3113         char *temp_unc;
3114         int rc = 0;
3115
3116         if (!ses->server->ops->tree_connect || !ses->server->ops->get_dfs_refer)
3117                 return -ENOSYS;
3118
3119         *num_referrals = 0;
3120         *referrals = NULL;
3121
3122         if (ses->ipc_tid == 0) {
3123                 temp_unc = kmalloc(2 /* for slashes */ +
3124                         strnlen(ses->serverName, SERVER_NAME_LEN_WITH_NULL * 2)
3125                                 + 1 + 4 /* slash IPC$ */ + 2, GFP_KERNEL);
3126                 if (temp_unc == NULL)
3127                         return -ENOMEM;
3128                 temp_unc[0] = '\\';
3129                 temp_unc[1] = '\\';
3130                 strcpy(temp_unc + 2, ses->serverName);
3131                 strcpy(temp_unc + 2 + strlen(ses->serverName), "\\IPC$");
3132                 rc = ses->server->ops->tree_connect(xid, ses, temp_unc, NULL,
3133                                                     nls_codepage);
3134                 cifs_dbg(FYI, "Tcon rc = %d ipc_tid = %d\n", rc, ses->ipc_tid);
3135                 kfree(temp_unc);
3136         }
3137         if (rc == 0)
3138                 rc = ses->server->ops->get_dfs_refer(xid, ses, old_path,
3139                                                      referrals, num_referrals,
3140                                                      nls_codepage, remap);
3141         /*
3142          * BB - map targetUNCs to dfs_info3 structures, here or in
3143          * ses->server->ops->get_dfs_refer.
3144          */
3145
3146         return rc;
3147 }
3148
3149 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3150 static struct lock_class_key cifs_key[2];
3151 static struct lock_class_key cifs_slock_key[2];
3152
3153 static inline void
3154 cifs_reclassify_socket4(struct socket *sock)
3155 {
3156         struct sock *sk = sock->sk;
3157         BUG_ON(!sock_allow_reclassification(sk));
3158         sock_lock_init_class_and_name(sk, "slock-AF_INET-CIFS",
3159                 &cifs_slock_key[0], "sk_lock-AF_INET-CIFS", &cifs_key[0]);
3160 }
3161
3162 static inline void
3163 cifs_reclassify_socket6(struct socket *sock)
3164 {
3165         struct sock *sk = sock->sk;
3166         BUG_ON(!sock_allow_reclassification(sk));
3167         sock_lock_init_class_and_name(sk, "slock-AF_INET6-CIFS",
3168                 &cifs_slock_key[1], "sk_lock-AF_INET6-CIFS", &cifs_key[1]);
3169 }
3170 #else
3171 static inline void
3172 cifs_reclassify_socket4(struct socket *sock)
3173 {
3174 }
3175
3176 static inline void
3177 cifs_reclassify_socket6(struct socket *sock)
3178 {
3179 }
3180 #endif
3181
3182 /* See RFC1001 section 14 on representation of Netbios names */
3183 static void rfc1002mangle(char *target, char *source, unsigned int length)
3184 {
3185         unsigned int i, j;
3186
3187         for (i = 0, j = 0; i < (length); i++) {
3188                 /* mask a nibble at a time and encode */
3189                 target[j] = 'A' + (0x0F & (source[i] >> 4));
3190                 target[j+1] = 'A' + (0x0F & source[i]);
3191                 j += 2;
3192         }
3193
3194 }
3195
3196 static int
3197 bind_socket(struct TCP_Server_Info *server)
3198 {
3199         int rc = 0;
3200         if (server->srcaddr.ss_family != AF_UNSPEC) {
3201                 /* Bind to the specified local IP address */
3202                 struct socket *socket = server->ssocket;
3203                 rc = socket->ops->bind(socket,
3204                                        (struct sockaddr *) &server->srcaddr,
3205                                        sizeof(server->srcaddr));
3206                 if (rc < 0) {
3207                         struct sockaddr_in *saddr4;
3208                         struct sockaddr_in6 *saddr6;
3209                         saddr4 = (struct sockaddr_in *)&server->srcaddr;
3210                         saddr6 = (struct sockaddr_in6 *)&server->srcaddr;
3211                         if (saddr6->sin6_family == AF_INET6)
3212                                 cifs_dbg(VFS, "Failed to bind to: %pI6c, error: %d\n",
3213                                          &saddr6->sin6_addr, rc);
3214                         else
3215                                 cifs_dbg(VFS, "Failed to bind to: %pI4, error: %d\n",
3216                                          &saddr4->sin_addr.s_addr, rc);
3217                 }
3218         }
3219         return rc;
3220 }
3221
3222 static int
3223 ip_rfc1001_connect(struct TCP_Server_Info *server)
3224 {
3225         int rc = 0;
3226         /*
3227          * some servers require RFC1001 sessinit before sending
3228          * negprot - BB check reconnection in case where second
3229          * sessinit is sent but no second negprot
3230          */
3231         struct rfc1002_session_packet *ses_init_buf;
3232         struct smb_hdr *smb_buf;
3233         ses_init_buf = kzalloc(sizeof(struct rfc1002_session_packet),
3234                                GFP_KERNEL);
3235         if (ses_init_buf) {
3236                 ses_init_buf->trailer.session_req.called_len = 32;
3237
3238                 if (server->server_RFC1001_name[0] != 0)
3239                         rfc1002mangle(ses_init_buf->trailer.
3240                                       session_req.called_name,
3241                                       server->server_RFC1001_name,
3242                                       RFC1001_NAME_LEN_WITH_NULL);
3243                 else
3244                         rfc1002mangle(ses_init_buf->trailer.
3245                                       session_req.called_name,
3246                                       DEFAULT_CIFS_CALLED_NAME,
3247                                       RFC1001_NAME_LEN_WITH_NULL);
3248
3249                 ses_init_buf->trailer.session_req.calling_len = 32;
3250
3251                 /*
3252                  * calling name ends in null (byte 16) from old smb
3253                  * convention.
3254                  */
3255                 if (server->workstation_RFC1001_name[0] != 0)
3256                         rfc1002mangle(ses_init_buf->trailer.
3257                                       session_req.calling_name,
3258                                       server->workstation_RFC1001_name,
3259                                       RFC1001_NAME_LEN_WITH_NULL);
3260                 else
3261                         rfc1002mangle(ses_init_buf->trailer.
3262                                       session_req.calling_name,
3263                                       "LINUX_CIFS_CLNT",
3264                                       RFC1001_NAME_LEN_WITH_NULL);
3265
3266                 ses_init_buf->trailer.session_req.scope1 = 0;
3267                 ses_init_buf->trailer.session_req.scope2 = 0;
3268                 smb_buf = (struct smb_hdr *)ses_init_buf;
3269
3270                 /* sizeof RFC1002_SESSION_REQUEST with no scope */
3271                 smb_buf->smb_buf_length = cpu_to_be32(0x81000044);
3272                 rc = smb_send(server, smb_buf, 0x44);
3273                 kfree(ses_init_buf);
3274                 /*
3275                  * RFC1001 layer in at least one server
3276                  * requires very short break before negprot
3277                  * presumably because not expecting negprot
3278                  * to follow so fast.  This is a simple
3279                  * solution that works without
3280                  * complicating the code and causes no
3281                  * significant slowing down on mount
3282                  * for everyone else
3283                  */
3284                 usleep_range(1000, 2000);
3285         }
3286         /*
3287          * else the negprot may still work without this
3288          * even though malloc failed
3289          */
3290
3291         return rc;
3292 }
3293
3294 static int
3295 generic_ip_connect(struct TCP_Server_Info *server)
3296 {
3297         int rc = 0;
3298         __be16 sport;
3299         int slen, sfamily;
3300         struct socket *socket = server->ssocket;
3301         struct sockaddr *saddr;
3302
3303         saddr = (struct sockaddr *) &server->dstaddr;
3304
3305         if (server->dstaddr.ss_family == AF_INET6) {
3306                 sport = ((struct sockaddr_in6 *) saddr)->sin6_port;
3307                 slen = sizeof(struct sockaddr_in6);
3308                 sfamily = AF_INET6;
3309         } else {
3310                 sport = ((struct sockaddr_in *) saddr)->sin_port;
3311                 slen = sizeof(struct sockaddr_in);
3312                 sfamily = AF_INET;
3313         }
3314
3315         if (socket == NULL) {
3316                 rc = __sock_create(cifs_net_ns(server), sfamily, SOCK_STREAM,
3317                                    IPPROTO_TCP, &socket, 1);
3318                 if (rc < 0) {
3319                         cifs_dbg(VFS, "Error %d creating socket\n", rc);
3320                         server->ssocket = NULL;
3321                         return rc;
3322                 }
3323
3324                 /* BB other socket options to set KEEPALIVE, NODELAY? */
3325                 cifs_dbg(FYI, "Socket created\n");
3326                 server->ssocket = socket;
3327                 socket->sk->sk_allocation = GFP_NOFS;
3328                 if (sfamily == AF_INET6)
3329                         cifs_reclassify_socket6(socket);
3330                 else
3331                         cifs_reclassify_socket4(socket);
3332         }
3333
3334         rc = bind_socket(server);
3335         if (rc < 0)
3336                 return rc;
3337
3338         /*
3339          * Eventually check for other socket options to change from
3340          * the default. sock_setsockopt not used because it expects
3341          * user space buffer
3342          */
3343         socket->sk->sk_rcvtimeo = 7 * HZ;
3344         socket->sk->sk_sndtimeo = 5 * HZ;
3345
3346         /* make the bufsizes depend on wsize/rsize and max requests */
3347         if (server->noautotune) {
3348                 if (socket->sk->sk_sndbuf < (200 * 1024))
3349                         socket->sk->sk_sndbuf = 200 * 1024;
3350                 if (socket->sk->sk_rcvbuf < (140 * 1024))
3351                         socket->sk->sk_rcvbuf = 140 * 1024;
3352         }
3353
3354         if (server->tcp_nodelay) {
3355                 int val = 1;
3356                 rc = kernel_setsockopt(socket, SOL_TCP, TCP_NODELAY,
3357                                 (char *)&val, sizeof(val));
3358                 if (rc)
3359                         cifs_dbg(FYI, "set TCP_NODELAY socket option error %d\n",
3360                                  rc);
3361         }
3362
3363         cifs_dbg(FYI, "sndbuf %d rcvbuf %d rcvtimeo 0x%lx\n",
3364                  socket->sk->sk_sndbuf,
3365                  socket->sk->sk_rcvbuf, socket->sk->sk_rcvtimeo);
3366
3367         rc = socket->ops->connect(socket, saddr, slen, 0);
3368         if (rc < 0) {
3369                 cifs_dbg(FYI, "Error %d connecting to server\n", rc);
3370                 sock_release(socket);
3371                 server->ssocket = NULL;
3372                 return rc;
3373         }
3374
3375         if (sport == htons(RFC1001_PORT))
3376                 rc = ip_rfc1001_connect(server);
3377
3378         return rc;
3379 }
3380
3381 static int
3382 ip_connect(struct TCP_Server_Info *server)
3383 {
3384         __be16 *sport;
3385         struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&server->dstaddr;
3386         struct sockaddr_in *addr = (struct sockaddr_in *)&server->dstaddr;
3387
3388         if (server->dstaddr.ss_family == AF_INET6)
3389                 sport = &addr6->sin6_port;
3390         else
3391                 sport = &addr->sin_port;
3392
3393         if (*sport == 0) {
3394                 int rc;
3395
3396                 /* try with 445 port at first */
3397                 *sport = htons(CIFS_PORT);
3398
3399                 rc = generic_ip_connect(server);
3400                 if (rc >= 0)
3401                         return rc;
3402
3403                 /* if it failed, try with 139 port */
3404                 *sport = htons(RFC1001_PORT);
3405         }
3406
3407         return generic_ip_connect(server);
3408 }
3409
3410 void reset_cifs_unix_caps(unsigned int xid, struct cifs_tcon *tcon,
3411                           struct cifs_sb_info *cifs_sb, struct smb_vol *vol_info)
3412 {
3413         /* if we are reconnecting then should we check to see if
3414          * any requested capabilities changed locally e.g. via
3415          * remount but we can not do much about it here
3416          * if they have (even if we could detect it by the following)
3417          * Perhaps we could add a backpointer to array of sb from tcon
3418          * or if we change to make all sb to same share the same
3419          * sb as NFS - then we only have one backpointer to sb.
3420          * What if we wanted to mount the server share twice once with
3421          * and once without posixacls or posix paths? */
3422         __u64 saved_cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3423
3424         if (vol_info && vol_info->no_linux_ext) {
3425                 tcon->fsUnixInfo.Capability = 0;
3426                 tcon->unix_ext = 0; /* Unix Extensions disabled */
3427                 cifs_dbg(FYI, "Linux protocol extensions disabled\n");
3428                 return;
3429         } else if (vol_info)
3430                 tcon->unix_ext = 1; /* Unix Extensions supported */
3431
3432         if (tcon->unix_ext == 0) {
3433                 cifs_dbg(FYI, "Unix extensions disabled so not set on reconnect\n");
3434                 return;
3435         }
3436
3437         if (!CIFSSMBQFSUnixInfo(xid, tcon)) {
3438                 __u64 cap = le64_to_cpu(tcon->fsUnixInfo.Capability);
3439                 cifs_dbg(FYI, "unix caps which server supports %lld\n", cap);
3440                 /* check for reconnect case in which we do not
3441                    want to change the mount behavior if we can avoid it */
3442                 if (vol_info == NULL) {
3443                         /* turn off POSIX ACL and PATHNAMES if not set
3444                            originally at mount time */
3445                         if ((saved_cap & CIFS_UNIX_POSIX_ACL_CAP) == 0)
3446                                 cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3447                         if ((saved_cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3448                                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3449                                         cifs_dbg(VFS, "POSIXPATH support change\n");
3450                                 cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3451                         } else if ((cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) == 0) {
3452                                 cifs_dbg(VFS, "possible reconnect error\n");
3453                                 cifs_dbg(VFS, "server disabled POSIX path support\n");
3454                         }
3455                 }
3456
3457                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3458                         cifs_dbg(VFS, "per-share encryption not supported yet\n");
3459
3460                 cap &= CIFS_UNIX_CAP_MASK;
3461                 if (vol_info && vol_info->no_psx_acl)
3462                         cap &= ~CIFS_UNIX_POSIX_ACL_CAP;
3463                 else if (CIFS_UNIX_POSIX_ACL_CAP & cap) {
3464                         cifs_dbg(FYI, "negotiated posix acl support\n");
3465                         if (cifs_sb)
3466                                 cifs_sb->mnt_cifs_flags |=
3467                                         CIFS_MOUNT_POSIXACL;
3468                 }
3469
3470                 if (vol_info && vol_info->posix_paths == 0)
3471                         cap &= ~CIFS_UNIX_POSIX_PATHNAMES_CAP;
3472                 else if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3473                         cifs_dbg(FYI, "negotiate posix pathnames\n");
3474                         if (cifs_sb)
3475                                 cifs_sb->mnt_cifs_flags |=
3476                                         CIFS_MOUNT_POSIX_PATHS;
3477                 }
3478
3479                 cifs_dbg(FYI, "Negotiate caps 0x%x\n", (int)cap);
3480 #ifdef CONFIG_CIFS_DEBUG2
3481                 if (cap & CIFS_UNIX_FCNTL_CAP)
3482                         cifs_dbg(FYI, "FCNTL cap\n");
3483                 if (cap & CIFS_UNIX_EXTATTR_CAP)
3484                         cifs_dbg(FYI, "EXTATTR cap\n");
3485                 if (cap & CIFS_UNIX_POSIX_PATHNAMES_CAP)
3486                         cifs_dbg(FYI, "POSIX path cap\n");
3487                 if (cap & CIFS_UNIX_XATTR_CAP)
3488                         cifs_dbg(FYI, "XATTR cap\n");
3489                 if (cap & CIFS_UNIX_POSIX_ACL_CAP)
3490                         cifs_dbg(FYI, "POSIX ACL cap\n");
3491                 if (cap & CIFS_UNIX_LARGE_READ_CAP)
3492                         cifs_dbg(FYI, "very large read cap\n");
3493                 if (cap & CIFS_UNIX_LARGE_WRITE_CAP)
3494                         cifs_dbg(FYI, "very large write cap\n");
3495                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP)
3496                         cifs_dbg(FYI, "transport encryption cap\n");
3497                 if (cap & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)
3498                         cifs_dbg(FYI, "mandatory transport encryption cap\n");
3499 #endif /* CIFS_DEBUG2 */
3500                 if (CIFSSMBSetFSUnixInfo(xid, tcon, cap)) {
3501                         if (vol_info == NULL) {
3502                                 cifs_dbg(FYI, "resetting capabilities failed\n");
3503                         } else
3504                                 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");
3505
3506                 }
3507         }
3508 }
3509
3510 int cifs_setup_cifs_sb(struct smb_vol *pvolume_info,
3511                         struct cifs_sb_info *cifs_sb)
3512 {
3513         INIT_DELAYED_WORK(&cifs_sb->prune_tlinks, cifs_prune_tlinks);
3514
3515         spin_lock_init(&cifs_sb->tlink_tree_lock);
3516         cifs_sb->tlink_tree = RB_ROOT;
3517
3518         /*
3519          * Temporarily set r/wsize for matching superblock. If we end up using
3520          * new sb then client will later negotiate it downward if needed.
3521          */
3522         cifs_sb->rsize = pvolume_info->rsize;
3523         cifs_sb->wsize = pvolume_info->wsize;
3524
3525         cifs_sb->mnt_uid = pvolume_info->linux_uid;
3526         cifs_sb->mnt_gid = pvolume_info->linux_gid;
3527         cifs_sb->mnt_file_mode = pvolume_info->file_mode;
3528         cifs_sb->mnt_dir_mode = pvolume_info->dir_mode;
3529         cifs_dbg(FYI, "file mode: %04ho  dir mode: %04ho\n",
3530                  cifs_sb->mnt_file_mode, cifs_sb->mnt_dir_mode);
3531
3532         cifs_sb->actimeo = pvolume_info->actimeo;
3533         cifs_sb->local_nls = pvolume_info->local_nls;
3534
3535         if (pvolume_info->noperm)
3536                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_PERM;
3537         if (pvolume_info->setuids)
3538                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SET_UID;
3539         if (pvolume_info->setuidfromacl)
3540                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UID_FROM_ACL;
3541         if (pvolume_info->server_ino)
3542                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_SERVER_INUM;
3543         if (pvolume_info->remap)
3544                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SFM_CHR;
3545         if (pvolume_info->sfu_remap)
3546                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MAP_SPECIAL_CHR;
3547         if (pvolume_info->no_xattr)
3548                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_XATTR;
3549         if (pvolume_info->sfu_emul)
3550                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_UNX_EMUL;
3551         if (pvolume_info->nobrl)
3552                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NO_BRL;
3553         if (pvolume_info->nostrictsync)
3554                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOSSYNC;
3555         if (pvolume_info->mand_lock)
3556                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_NOPOSIXBRL;
3557         if (pvolume_info->rwpidforward)
3558                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_RWPIDFORWARD;
3559         if (pvolume_info->cifs_acl)
3560                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_ACL;
3561         if (pvolume_info->backupuid_specified) {
3562                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_BACKUPUID;
3563                 cifs_sb->mnt_backupuid = pvolume_info->backupuid;
3564         }
3565         if (pvolume_info->backupgid_specified) {
3566                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_CIFS_BACKUPGID;
3567                 cifs_sb->mnt_backupgid = pvolume_info->backupgid;
3568         }
3569         if (pvolume_info->override_uid)
3570                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_UID;
3571         if (pvolume_info->override_gid)
3572                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_OVERR_GID;
3573         if (pvolume_info->dynperm)
3574                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DYNPERM;
3575         if (pvolume_info->fsc)
3576                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_FSCACHE;
3577         if (pvolume_info->multiuser)
3578                 cifs_sb->mnt_cifs_flags |= (CIFS_MOUNT_MULTIUSER |
3579                                             CIFS_MOUNT_NO_PERM);
3580         if (pvolume_info->strict_io)
3581                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_STRICT_IO;
3582         if (pvolume_info->direct_io) {
3583                 cifs_dbg(FYI, "mounting share using direct i/o\n");
3584                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_DIRECT_IO;
3585         }
3586         if (pvolume_info->mfsymlinks) {
3587                 if (pvolume_info->sfu_emul) {
3588                         /*
3589                          * Our SFU ("Services for Unix" emulation does not allow
3590                          * creating symlinks but does allow reading existing SFU
3591                          * symlinks (it does allow both creating and reading SFU
3592                          * style mknod and FIFOs though). When "mfsymlinks" and
3593                          * "sfu" are both enabled at the same time, it allows
3594                          * reading both types of symlinks, but will only create
3595                          * them with mfsymlinks format. This allows better
3596                          * Apple compatibility (probably better for Samba too)
3597                          * while still recognizing old Windows style symlinks.
3598                          */
3599                         cifs_dbg(VFS, "mount options mfsymlinks and sfu both enabled\n");
3600                 }
3601                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_MF_SYMLINKS;
3602         }
3603
3604         if ((pvolume_info->cifs_acl) && (pvolume_info->dynperm))
3605                 cifs_dbg(VFS, "mount option dynperm ignored if cifsacl mount option supported\n");
3606
3607         if (pvolume_info->prepath) {
3608                 cifs_sb->prepath = kstrdup(pvolume_info->prepath, GFP_KERNEL);
3609                 if (cifs_sb->prepath == NULL)
3610                         return -ENOMEM;
3611         }
3612
3613         return 0;
3614 }
3615
3616 static void
3617 cleanup_volume_info_contents(struct smb_vol *volume_info)
3618 {
3619         kfree(volume_info->username);
3620         kzfree(volume_info->password);
3621         kfree(volume_info->UNC);
3622         kfree(volume_info->domainname);
3623         kfree(volume_info->iocharset);
3624         kfree(volume_info->prepath);
3625 }
3626
3627 void
3628 cifs_cleanup_volume_info(struct smb_vol *volume_info)
3629 {
3630         if (!volume_info)
3631                 return;
3632         cleanup_volume_info_contents(volume_info);
3633         kfree(volume_info);
3634 }
3635
3636
3637 #ifdef CONFIG_CIFS_DFS_UPCALL
3638 /*
3639  * cifs_build_path_to_root returns full path to root when we do not have an
3640  * exiting connection (tcon)
3641  */
3642 static char *
3643 build_unc_path_to_root(const struct smb_vol *vol,
3644                 const struct cifs_sb_info *cifs_sb)
3645 {
3646         char *full_path, *pos;
3647         unsigned int pplen = vol->prepath ? strlen(vol->prepath) + 1 : 0;
3648         unsigned int unc_len = strnlen(vol->UNC, MAX_TREE_SIZE + 1);
3649
3650         full_path = kmalloc(unc_len + pplen + 1, GFP_KERNEL);
3651         if (full_path == NULL)
3652                 return ERR_PTR(-ENOMEM);
3653
3654         strncpy(full_path, vol->UNC, unc_len);
3655         pos = full_path + unc_len;
3656
3657         if (pplen) {
3658                 *pos = CIFS_DIR_SEP(cifs_sb);
3659                 strncpy(pos + 1, vol->prepath, pplen);
3660                 pos += pplen;
3661         }
3662
3663         *pos = '\0'; /* add trailing null */
3664         convert_delimiter(full_path, CIFS_DIR_SEP(cifs_sb));
3665         cifs_dbg(FYI, "%s: full_path=%s\n", __func__, full_path);
3666         return full_path;
3667 }
3668
3669 /*
3670  * Perform a dfs referral query for a share and (optionally) prefix
3671  *
3672  * If a referral is found, cifs_sb->mountdata will be (re-)allocated
3673  * to a string containing updated options for the submount.  Otherwise it
3674  * will be left untouched.
3675  *
3676  * Returns the rc from get_dfs_path to the caller, which can be used to
3677  * determine whether there were referrals.
3678  */
3679 static int
3680 expand_dfs_referral(const unsigned int xid, struct cifs_ses *ses,
3681                     struct smb_vol *volume_info, struct cifs_sb_info *cifs_sb,
3682                     int check_prefix)
3683 {
3684         int rc;
3685         unsigned int num_referrals = 0;
3686         struct dfs_info3_param *referrals = NULL;
3687         char *full_path = NULL, *ref_path = NULL, *mdata = NULL;
3688
3689         full_path = build_unc_path_to_root(volume_info, cifs_sb);
3690         if (IS_ERR(full_path))
3691                 return PTR_ERR(full_path);
3692
3693         /* For DFS paths, skip the first '\' of the UNC */
3694         ref_path = check_prefix ? full_path + 1 : volume_info->UNC + 1;
3695
3696         rc = get_dfs_path(xid, ses, ref_path, cifs_sb->local_nls,
3697                           &num_referrals, &referrals, cifs_remap(cifs_sb));
3698
3699         if (!rc && num_referrals > 0) {
3700                 char *fake_devname = NULL;
3701
3702                 mdata = cifs_compose_mount_options(cifs_sb->mountdata,
3703                                                    full_path + 1, referrals,
3704                                                    &fake_devname);
3705
3706                 free_dfs_info_array(referrals, num_referrals);
3707
3708                 if (IS_ERR(mdata)) {
3709                         rc = PTR_ERR(mdata);
3710                         mdata = NULL;
3711                 } else {
3712                         cleanup_volume_info_contents(volume_info);
3713                         rc = cifs_setup_volume_info(volume_info, mdata,
3714                                                         fake_devname);
3715                 }
3716                 kfree(fake_devname);
3717                 kfree(cifs_sb->mountdata);
3718                 cifs_sb->mountdata = mdata;
3719         }
3720         kfree(full_path);
3721         return rc;
3722 }
3723 #endif
3724
3725 static int
3726 cifs_setup_volume_info(struct smb_vol *volume_info, char *mount_data,
3727                         const char *devname)
3728 {
3729         int rc = 0;
3730
3731         if (cifs_parse_mount_options(mount_data, devname, volume_info))
3732                 return -EINVAL;
3733
3734         if (volume_info->nullauth) {
3735                 cifs_dbg(FYI, "Anonymous login\n");
3736                 kfree(volume_info->username);
3737                 volume_info->username = NULL;
3738         } else if (volume_info->username) {
3739                 /* BB fixme parse for domain name here */
3740                 cifs_dbg(FYI, "Username: %s\n", volume_info->username);
3741         } else {
3742                 cifs_dbg(VFS, "No username specified\n");
3743         /* In userspace mount helper we can get user name from alternate
3744            locations such as env variables and files on disk */
3745                 return -EINVAL;
3746         }
3747
3748         /* this is needed for ASCII cp to Unicode converts */
3749         if (volume_info->iocharset == NULL) {
3750                 /* load_nls_default cannot return null */
3751                 volume_info->local_nls = load_nls_default();
3752         } else {
3753                 volume_info->local_nls = load_nls(volume_info->iocharset);
3754                 if (volume_info->local_nls == NULL) {
3755                         cifs_dbg(VFS, "CIFS mount error: iocharset %s not found\n",
3756                                  volume_info->iocharset);
3757                         return -ELIBACC;
3758                 }
3759         }
3760
3761         return rc;
3762 }
3763
3764 struct smb_vol *
3765 cifs_get_volume_info(char *mount_data, const char *devname)
3766 {
3767         int rc;
3768         struct smb_vol *volume_info;
3769
3770         volume_info = kmalloc(sizeof(struct smb_vol), GFP_KERNEL);
3771         if (!volume_info)
3772                 return ERR_PTR(-ENOMEM);
3773
3774         rc = cifs_setup_volume_info(volume_info, mount_data, devname);
3775         if (rc) {
3776                 cifs_cleanup_volume_info(volume_info);
3777                 volume_info = ERR_PTR(rc);
3778         }
3779
3780         return volume_info;
3781 }
3782
3783 static int
3784 cifs_are_all_path_components_accessible(struct TCP_Server_Info *server,
3785                                         unsigned int xid,
3786                                         struct cifs_tcon *tcon,
3787                                         struct cifs_sb_info *cifs_sb,
3788                                         char *full_path)
3789 {
3790         int rc;
3791         char *s;
3792         char sep, tmp;
3793
3794         sep = CIFS_DIR_SEP(cifs_sb);
3795         s = full_path;
3796
3797         rc = server->ops->is_path_accessible(xid, tcon, cifs_sb, "");
3798         while (rc == 0) {
3799                 /* skip separators */
3800                 while (*s == sep)
3801                         s++;
3802                 if (!*s)
3803                         break;
3804                 /* next separator */
3805                 while (*s && *s != sep)
3806                         s++;
3807
3808                 /*
3809                  * temporarily null-terminate the path at the end of
3810                  * the current component
3811                  */
3812                 tmp = *s;
3813                 *s = 0;
3814                 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3815                                                      full_path);
3816                 *s = tmp;
3817         }
3818         return rc;
3819 }
3820
3821 int
3822 cifs_mount(struct cifs_sb_info *cifs_sb, struct smb_vol *volume_info)
3823 {
3824         int rc;
3825         unsigned int xid;
3826         struct cifs_ses *ses;
3827         struct cifs_tcon *tcon;
3828         struct TCP_Server_Info *server;
3829         char   *full_path;
3830         struct tcon_link *tlink;
3831 #ifdef CONFIG_CIFS_DFS_UPCALL
3832         int referral_walks_count = 0;
3833 #endif
3834
3835 #ifdef CONFIG_CIFS_DFS_UPCALL
3836 try_mount_again:
3837         /* cleanup activities if we're chasing a referral */
3838         if (referral_walks_count) {
3839                 if (tcon)
3840                         cifs_put_tcon(tcon);
3841                 else if (ses)
3842                         cifs_put_smb_ses(ses);
3843
3844                 cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_POSIX_PATHS;
3845
3846                 free_xid(xid);
3847         }
3848 #endif
3849         rc = 0;
3850         tcon = NULL;
3851         ses = NULL;
3852         server = NULL;
3853         full_path = NULL;
3854         tlink = NULL;
3855
3856         xid = get_xid();
3857
3858         /* get a reference to a tcp session */
3859         server = cifs_get_tcp_session(volume_info);
3860         if (IS_ERR(server)) {
3861                 rc = PTR_ERR(server);
3862                 goto out;
3863         }
3864         if ((volume_info->max_credits < 20) ||
3865              (volume_info->max_credits > 60000))
3866                 server->max_credits = SMB2_MAX_CREDITS_AVAILABLE;
3867         else
3868                 server->max_credits = volume_info->max_credits;
3869         /* get a reference to a SMB session */
3870         ses = cifs_get_smb_ses(server, volume_info);
3871         if (IS_ERR(ses)) {
3872                 rc = PTR_ERR(ses);
3873                 ses = NULL;
3874                 goto mount_fail_check;
3875         }
3876
3877         if ((volume_info->persistent == true) && ((ses->server->capabilities &
3878                 SMB2_GLOBAL_CAP_PERSISTENT_HANDLES) == 0)) {
3879                 cifs_dbg(VFS, "persistent handles not supported by server\n");
3880                 rc = -EOPNOTSUPP;
3881                 goto mount_fail_check;
3882         }
3883
3884         /* search for existing tcon to this server share */
3885         tcon = cifs_get_tcon(ses, volume_info);
3886         if (IS_ERR(tcon)) {
3887                 rc = PTR_ERR(tcon);
3888                 tcon = NULL;
3889                 if (rc == -EACCES)
3890                         goto mount_fail_check;
3891
3892                 goto remote_path_check;
3893         }
3894
3895         /* tell server which Unix caps we support */
3896         if (cap_unix(tcon->ses)) {
3897                 /* reset of caps checks mount to see if unix extensions
3898                    disabled for just this mount */
3899                 reset_cifs_unix_caps(xid, tcon, cifs_sb, volume_info);
3900                 if ((tcon->ses->server->tcpStatus == CifsNeedReconnect) &&
3901                     (le64_to_cpu(tcon->fsUnixInfo.Capability) &
3902                      CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP)) {
3903                         rc = -EACCES;
3904                         goto mount_fail_check;
3905                 }
3906         } else
3907                 tcon->unix_ext = 0; /* server does not support them */
3908
3909         /* do not care if a following call succeed - informational */
3910         if (!tcon->ipc && server->ops->qfs_tcon)
3911                 server->ops->qfs_tcon(xid, tcon);
3912
3913         cifs_sb->wsize = server->ops->negotiate_wsize(tcon, volume_info);
3914         cifs_sb->rsize = server->ops->negotiate_rsize(tcon, volume_info);
3915
3916 remote_path_check:
3917 #ifdef CONFIG_CIFS_DFS_UPCALL
3918         /*
3919          * Perform an unconditional check for whether there are DFS
3920          * referrals for this path without prefix, to provide support
3921          * for DFS referrals from w2k8 servers which don't seem to respond
3922          * with PATH_NOT_COVERED to requests that include the prefix.
3923          * Chase the referral if found, otherwise continue normally.
3924          */
3925         if (referral_walks_count == 0) {
3926                 int refrc = expand_dfs_referral(xid, ses, volume_info, cifs_sb,
3927                                                 false);
3928                 if (!refrc) {
3929                         referral_walks_count++;
3930                         goto try_mount_again;
3931                 }
3932         }
3933 #endif
3934
3935         /* check if a whole path is not remote */
3936         if (!rc && tcon) {
3937                 if (!server->ops->is_path_accessible) {
3938                         rc = -ENOSYS;
3939                         goto mount_fail_check;
3940                 }
3941                 /*
3942                  * cifs_build_path_to_root works only when we have a valid tcon
3943                  */
3944                 full_path = cifs_build_path_to_root(volume_info, cifs_sb, tcon,
3945                                         tcon->Flags & SMB_SHARE_IS_IN_DFS);
3946                 if (full_path == NULL) {
3947                         rc = -ENOMEM;
3948                         goto mount_fail_check;
3949                 }
3950                 rc = server->ops->is_path_accessible(xid, tcon, cifs_sb,
3951                                                      full_path);
3952                 if (rc != 0 && rc != -EREMOTE) {
3953                         kfree(full_path);
3954                         goto mount_fail_check;
3955                 }
3956
3957                 if (rc != -EREMOTE) {
3958                         rc = cifs_are_all_path_components_accessible(server,
3959                                                              xid, tcon, cifs_sb,
3960                                                              full_path);
3961                         if (rc != 0) {
3962                                 cifs_dbg(VFS, "cannot query dirs between root and final path, "
3963                                          "enabling CIFS_MOUNT_USE_PREFIX_PATH\n");
3964                                 cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
3965                                 rc = 0;
3966                         }
3967                 }
3968                 kfree(full_path);
3969         }
3970
3971         /* get referral if needed */
3972         if (rc == -EREMOTE) {
3973 #ifdef CONFIG_CIFS_DFS_UPCALL
3974                 if (referral_walks_count > MAX_NESTED_LINKS) {
3975                         /*
3976                          * BB: when we implement proper loop detection,
3977                          *     we will remove this check. But now we need it
3978                          *     to prevent an indefinite loop if 'DFS tree' is
3979                          *     misconfigured (i.e. has loops).
3980                          */
3981                         rc = -ELOOP;
3982                         goto mount_fail_check;
3983                 }
3984
3985                 rc = expand_dfs_referral(xid, ses, volume_info, cifs_sb, true);
3986
3987                 if (!rc) {
3988                         referral_walks_count++;
3989                         goto try_mount_again;
3990                 }
3991                 goto mount_fail_check;
3992 #else /* No DFS support, return error on mount */
3993                 rc = -EOPNOTSUPP;
3994 #endif
3995         }
3996
3997         if (rc)
3998                 goto mount_fail_check;
3999
4000         /* now, hang the tcon off of the superblock */
4001         tlink = kzalloc(sizeof *tlink, GFP_KERNEL);
4002         if (tlink == NULL) {
4003                 rc = -ENOMEM;
4004                 goto mount_fail_check;
4005         }
4006
4007         tlink->tl_uid = ses->linux_uid;
4008         tlink->tl_tcon = tcon;
4009         tlink->tl_time = jiffies;
4010         set_bit(TCON_LINK_MASTER, &tlink->tl_flags);
4011         set_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4012
4013         cifs_sb->master_tlink = tlink;
4014         spin_lock(&cifs_sb->tlink_tree_lock);
4015         tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4016         spin_unlock(&cifs_sb->tlink_tree_lock);
4017
4018         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4019                                 TLINK_IDLE_EXPIRE);
4020
4021 mount_fail_check:
4022         /* on error free sesinfo and tcon struct if needed */
4023         if (rc) {
4024                 /* If find_unc succeeded then rc == 0 so we can not end */
4025                 /* up accidentally freeing someone elses tcon struct */
4026                 if (tcon)
4027                         cifs_put_tcon(tcon);
4028                 else if (ses)
4029                         cifs_put_smb_ses(ses);
4030                 else
4031                         cifs_put_tcp_session(server, 0);
4032         }
4033
4034 out:
4035         free_xid(xid);
4036         return rc;
4037 }
4038
4039 /*
4040  * Issue a TREE_CONNECT request. Note that for IPC$ shares, that the tcon
4041  * pointer may be NULL.
4042  */
4043 int
4044 CIFSTCon(const unsigned int xid, struct cifs_ses *ses,
4045          const char *tree, struct cifs_tcon *tcon,
4046          const struct nls_table *nls_codepage)
4047 {
4048         struct smb_hdr *smb_buffer;
4049         struct smb_hdr *smb_buffer_response;
4050         TCONX_REQ *pSMB;
4051         TCONX_RSP *pSMBr;
4052         unsigned char *bcc_ptr;
4053         int rc = 0;
4054         int length;
4055         __u16 bytes_left, count;
4056
4057         if (ses == NULL)
4058                 return -EIO;
4059
4060         smb_buffer = cifs_buf_get();
4061         if (smb_buffer == NULL)
4062                 return -ENOMEM;
4063
4064         smb_buffer_response = smb_buffer;
4065
4066         header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX,
4067                         NULL /*no tid */ , 4 /*wct */ );
4068
4069         smb_buffer->Mid = get_next_mid(ses->server);
4070         smb_buffer->Uid = ses->Suid;
4071         pSMB = (TCONX_REQ *) smb_buffer;
4072         pSMBr = (TCONX_RSP *) smb_buffer_response;
4073
4074         pSMB->AndXCommand = 0xFF;
4075         pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO);
4076         bcc_ptr = &pSMB->Password[0];
4077         if (!tcon || (ses->server->sec_mode & SECMODE_USER)) {
4078                 pSMB->PasswordLength = cpu_to_le16(1);  /* minimum */
4079                 *bcc_ptr = 0; /* password is null byte */
4080                 bcc_ptr++;              /* skip password */
4081                 /* already aligned so no need to do it below */
4082         } else {
4083                 pSMB->PasswordLength = cpu_to_le16(CIFS_AUTH_RESP_SIZE);
4084                 /* BB FIXME add code to fail this if NTLMv2 or Kerberos
4085                    specified as required (when that support is added to
4086                    the vfs in the future) as only NTLM or the much
4087                    weaker LANMAN (which we do not send by default) is accepted
4088                    by Samba (not sure whether other servers allow
4089                    NTLMv2 password here) */
4090 #ifdef CONFIG_CIFS_WEAK_PW_HASH
4091                 if ((global_secflags & CIFSSEC_MAY_LANMAN) &&
4092                     (ses->sectype == LANMAN))
4093                         calc_lanman_hash(tcon->password, ses->server->cryptkey,
4094                                          ses->server->sec_mode &
4095                                             SECMODE_PW_ENCRYPT ? true : false,
4096                                          bcc_ptr);
4097                 else
4098 #endif /* CIFS_WEAK_PW_HASH */
4099                 rc = SMBNTencrypt(tcon->password, ses->server->cryptkey,
4100                                         bcc_ptr, nls_codepage);
4101                 if (rc) {
4102                         cifs_dbg(FYI, "%s Can't generate NTLM rsp. Error: %d\n",
4103                                  __func__, rc);
4104                         cifs_buf_release(smb_buffer);
4105                         return rc;
4106                 }
4107
4108                 bcc_ptr += CIFS_AUTH_RESP_SIZE;
4109                 if (ses->capabilities & CAP_UNICODE) {
4110                         /* must align unicode strings */
4111                         *bcc_ptr = 0; /* null byte password */
4112                         bcc_ptr++;
4113                 }
4114         }
4115
4116         if (ses->server->sign)
4117                 smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
4118
4119         if (ses->capabilities & CAP_STATUS32) {
4120                 smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS;
4121         }
4122         if (ses->capabilities & CAP_DFS) {
4123                 smb_buffer->Flags2 |= SMBFLG2_DFS;
4124         }
4125         if (ses->capabilities & CAP_UNICODE) {
4126                 smb_buffer->Flags2 |= SMBFLG2_UNICODE;
4127                 length =
4128                     cifs_strtoUTF16((__le16 *) bcc_ptr, tree,
4129                         6 /* max utf8 char length in bytes */ *
4130                         (/* server len*/ + 256 /* share len */), nls_codepage);
4131                 bcc_ptr += 2 * length;  /* convert num 16 bit words to bytes */
4132                 bcc_ptr += 2;   /* skip trailing null */
4133         } else {                /* ASCII */
4134                 strcpy(bcc_ptr, tree);
4135                 bcc_ptr += strlen(tree) + 1;
4136         }
4137         strcpy(bcc_ptr, "?????");
4138         bcc_ptr += strlen("?????");
4139         bcc_ptr += 1;
4140         count = bcc_ptr - &pSMB->Password[0];
4141         pSMB->hdr.smb_buf_length = cpu_to_be32(be32_to_cpu(
4142                                         pSMB->hdr.smb_buf_length) + count);
4143         pSMB->ByteCount = cpu_to_le16(count);
4144
4145         rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length,
4146                          0);
4147
4148         /* above now done in SendReceive */
4149         if ((rc == 0) && (tcon != NULL)) {
4150                 bool is_unicode;
4151
4152                 tcon->tidStatus = CifsGood;
4153                 tcon->need_reconnect = false;
4154                 tcon->tid = smb_buffer_response->Tid;
4155                 bcc_ptr = pByteArea(smb_buffer_response);
4156                 bytes_left = get_bcc(smb_buffer_response);
4157                 length = strnlen(bcc_ptr, bytes_left - 2);
4158                 if (smb_buffer->Flags2 & SMBFLG2_UNICODE)
4159                         is_unicode = true;
4160                 else
4161                         is_unicode = false;
4162
4163
4164                 /* skip service field (NB: this field is always ASCII) */
4165                 if (length == 3) {
4166                         if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') &&
4167                             (bcc_ptr[2] == 'C')) {
4168                                 cifs_dbg(FYI, "IPC connection\n");
4169                                 tcon->ipc = 1;
4170                         }
4171                 } else if (length == 2) {
4172                         if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) {
4173                                 /* the most common case */
4174                                 cifs_dbg(FYI, "disk share connection\n");
4175                         }
4176                 }
4177                 bcc_ptr += length + 1;
4178                 bytes_left -= (length + 1);
4179                 strlcpy(tcon->treeName, tree, sizeof(tcon->treeName));
4180
4181                 /* mostly informational -- no need to fail on error here */
4182                 kfree(tcon->nativeFileSystem);
4183                 tcon->nativeFileSystem = cifs_strndup_from_utf16(bcc_ptr,
4184                                                       bytes_left, is_unicode,
4185                                                       nls_codepage);
4186
4187                 cifs_dbg(FYI, "nativeFileSystem=%s\n", tcon->nativeFileSystem);
4188
4189                 if ((smb_buffer_response->WordCount == 3) ||
4190                          (smb_buffer_response->WordCount == 7))
4191                         /* field is in same location */
4192                         tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport);
4193                 else
4194                         tcon->Flags = 0;
4195                 cifs_dbg(FYI, "Tcon flags: 0x%x\n", tcon->Flags);
4196         } else if ((rc == 0) && tcon == NULL) {
4197                 /* all we need to save for IPC$ connection */
4198                 ses->ipc_tid = smb_buffer_response->Tid;
4199         }
4200
4201         cifs_buf_release(smb_buffer);
4202         return rc;
4203 }
4204
4205 static void delayed_free(struct rcu_head *p)
4206 {
4207         struct cifs_sb_info *sbi = container_of(p, struct cifs_sb_info, rcu);
4208         unload_nls(sbi->local_nls);
4209         kfree(sbi);
4210 }
4211
4212 void
4213 cifs_umount(struct cifs_sb_info *cifs_sb)
4214 {
4215         struct rb_root *root = &cifs_sb->tlink_tree;
4216         struct rb_node *node;
4217         struct tcon_link *tlink;
4218
4219         cancel_delayed_work_sync(&cifs_sb->prune_tlinks);
4220
4221         spin_lock(&cifs_sb->tlink_tree_lock);
4222         while ((node = rb_first(root))) {
4223                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4224                 cifs_get_tlink(tlink);
4225                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4226                 rb_erase(node, root);
4227
4228                 spin_unlock(&cifs_sb->tlink_tree_lock);
4229                 cifs_put_tlink(tlink);
4230                 spin_lock(&cifs_sb->tlink_tree_lock);
4231         }
4232         spin_unlock(&cifs_sb->tlink_tree_lock);
4233
4234         kfree(cifs_sb->mountdata);
4235         kfree(cifs_sb->prepath);
4236         call_rcu(&cifs_sb->rcu, delayed_free);
4237 }
4238
4239 int
4240 cifs_negotiate_protocol(const unsigned int xid, struct cifs_ses *ses)
4241 {
4242         int rc = 0;
4243         struct TCP_Server_Info *server = ses->server;
4244
4245         if (!server->ops->need_neg || !server->ops->negotiate)
4246                 return -ENOSYS;
4247
4248         /* only send once per connect */
4249         if (!server->ops->need_neg(server))
4250                 return 0;
4251
4252         set_credits(server, 1);
4253
4254         rc = server->ops->negotiate(xid, ses);
4255         if (rc == 0) {
4256                 spin_lock(&GlobalMid_Lock);
4257                 if (server->tcpStatus == CifsNeedNegotiate)
4258                         server->tcpStatus = CifsGood;
4259                 else
4260                         rc = -EHOSTDOWN;
4261                 spin_unlock(&GlobalMid_Lock);
4262         }
4263
4264         return rc;
4265 }
4266
4267 int
4268 cifs_setup_session(const unsigned int xid, struct cifs_ses *ses,
4269                    struct nls_table *nls_info)
4270 {
4271         int rc = -ENOSYS;
4272         struct TCP_Server_Info *server = ses->server;
4273
4274         ses->capabilities = server->capabilities;
4275         if (linuxExtEnabled == 0)
4276                 ses->capabilities &= (~server->vals->cap_unix);
4277
4278         cifs_dbg(FYI, "Security Mode: 0x%x Capabilities: 0x%x TimeAdjust: %d\n",
4279                  server->sec_mode, server->capabilities, server->timeAdj);
4280
4281         if (ses->auth_key.response) {
4282                 cifs_dbg(VFS, "Free previous auth_key.response = %p\n",
4283                          ses->auth_key.response);
4284                 kfree(ses->auth_key.response);
4285                 ses->auth_key.response = NULL;
4286                 ses->auth_key.len = 0;
4287         }
4288
4289         if (server->ops->sess_setup)
4290                 rc = server->ops->sess_setup(xid, ses, nls_info);
4291
4292         if (rc)
4293                 cifs_dbg(VFS, "Send error in SessSetup = %d\n", rc);
4294
4295         return rc;
4296 }
4297
4298 static int
4299 cifs_set_vol_auth(struct smb_vol *vol, struct cifs_ses *ses)
4300 {
4301         vol->sectype = ses->sectype;
4302
4303         /* krb5 is special, since we don't need username or pw */
4304         if (vol->sectype == Kerberos)
4305                 return 0;
4306
4307         return cifs_set_cifscreds(vol, ses);
4308 }
4309
4310 static struct cifs_tcon *
4311 cifs_construct_tcon(struct cifs_sb_info *cifs_sb, kuid_t fsuid)
4312 {
4313         int rc;
4314         struct cifs_tcon *master_tcon = cifs_sb_master_tcon(cifs_sb);
4315         struct cifs_ses *ses;
4316         struct cifs_tcon *tcon = NULL;
4317         struct smb_vol *vol_info;
4318
4319         vol_info = kzalloc(sizeof(*vol_info), GFP_KERNEL);
4320         if (vol_info == NULL)
4321                 return ERR_PTR(-ENOMEM);
4322
4323         vol_info->local_nls = cifs_sb->local_nls;
4324         vol_info->linux_uid = fsuid;
4325         vol_info->cred_uid = fsuid;
4326         vol_info->UNC = master_tcon->treeName;
4327         vol_info->retry = master_tcon->retry;
4328         vol_info->nocase = master_tcon->nocase;
4329         vol_info->local_lease = master_tcon->local_lease;
4330         vol_info->resilient = master_tcon->use_resilient;
4331         vol_info->persistent = master_tcon->use_persistent;
4332         vol_info->no_linux_ext = !master_tcon->unix_ext;
4333         vol_info->sectype = master_tcon->ses->sectype;
4334         vol_info->sign = master_tcon->ses->sign;
4335         vol_info->seal = master_tcon->seal;
4336
4337         rc = cifs_set_vol_auth(vol_info, master_tcon->ses);
4338         if (rc) {
4339                 tcon = ERR_PTR(rc);
4340                 goto out;
4341         }
4342
4343         /* get a reference for the same TCP session */
4344         spin_lock(&cifs_tcp_ses_lock);
4345         ++master_tcon->ses->server->srv_count;
4346         spin_unlock(&cifs_tcp_ses_lock);
4347
4348         ses = cifs_get_smb_ses(master_tcon->ses->server, vol_info);
4349         if (IS_ERR(ses)) {
4350                 tcon = (struct cifs_tcon *)ses;
4351                 cifs_put_tcp_session(master_tcon->ses->server, 0);
4352                 goto out;
4353         }
4354
4355         tcon = cifs_get_tcon(ses, vol_info);
4356         if (IS_ERR(tcon)) {
4357                 cifs_put_smb_ses(ses);
4358                 goto out;
4359         }
4360
4361         if (cap_unix(ses))
4362                 reset_cifs_unix_caps(0, tcon, NULL, vol_info);
4363 out:
4364         kfree(vol_info->username);
4365         kzfree(vol_info->password);
4366         kfree(vol_info);
4367
4368         return tcon;
4369 }
4370
4371 struct cifs_tcon *
4372 cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb)
4373 {
4374         return tlink_tcon(cifs_sb_master_tlink(cifs_sb));
4375 }
4376
4377 /* find and return a tlink with given uid */
4378 static struct tcon_link *
4379 tlink_rb_search(struct rb_root *root, kuid_t uid)
4380 {
4381         struct rb_node *node = root->rb_node;
4382         struct tcon_link *tlink;
4383
4384         while (node) {
4385                 tlink = rb_entry(node, struct tcon_link, tl_rbnode);
4386
4387                 if (uid_gt(tlink->tl_uid, uid))
4388                         node = node->rb_left;
4389                 else if (uid_lt(tlink->tl_uid, uid))
4390                         node = node->rb_right;
4391                 else
4392                         return tlink;
4393         }
4394         return NULL;
4395 }
4396
4397 /* insert a tcon_link into the tree */
4398 static void
4399 tlink_rb_insert(struct rb_root *root, struct tcon_link *new_tlink)
4400 {
4401         struct rb_node **new = &(root->rb_node), *parent = NULL;
4402         struct tcon_link *tlink;
4403
4404         while (*new) {
4405                 tlink = rb_entry(*new, struct tcon_link, tl_rbnode);
4406                 parent = *new;
4407
4408                 if (uid_gt(tlink->tl_uid, new_tlink->tl_uid))
4409                         new = &((*new)->rb_left);
4410                 else
4411                         new = &((*new)->rb_right);
4412         }
4413
4414         rb_link_node(&new_tlink->tl_rbnode, parent, new);
4415         rb_insert_color(&new_tlink->tl_rbnode, root);
4416 }
4417
4418 /*
4419  * Find or construct an appropriate tcon given a cifs_sb and the fsuid of the
4420  * current task.
4421  *
4422  * If the superblock doesn't refer to a multiuser mount, then just return
4423  * the master tcon for the mount.
4424  *
4425  * First, search the rbtree for an existing tcon for this fsuid. If one
4426  * exists, then check to see if it's pending construction. If it is then wait
4427  * for construction to complete. Once it's no longer pending, check to see if
4428  * it failed and either return an error or retry construction, depending on
4429  * the timeout.
4430  *
4431  * If one doesn't exist then insert a new tcon_link struct into the tree and
4432  * try to construct a new one.
4433  */
4434 struct tcon_link *
4435 cifs_sb_tlink(struct cifs_sb_info *cifs_sb)
4436 {
4437         int ret;
4438         kuid_t fsuid = current_fsuid();
4439         struct tcon_link *tlink, *newtlink;
4440
4441         if (!(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER))
4442                 return cifs_get_tlink(cifs_sb_master_tlink(cifs_sb));
4443
4444         spin_lock(&cifs_sb->tlink_tree_lock);
4445         tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4446         if (tlink)
4447                 cifs_get_tlink(tlink);
4448         spin_unlock(&cifs_sb->tlink_tree_lock);
4449
4450         if (tlink == NULL) {
4451                 newtlink = kzalloc(sizeof(*tlink), GFP_KERNEL);
4452                 if (newtlink == NULL)
4453                         return ERR_PTR(-ENOMEM);
4454                 newtlink->tl_uid = fsuid;
4455                 newtlink->tl_tcon = ERR_PTR(-EACCES);
4456                 set_bit(TCON_LINK_PENDING, &newtlink->tl_flags);
4457                 set_bit(TCON_LINK_IN_TREE, &newtlink->tl_flags);
4458                 cifs_get_tlink(newtlink);
4459
4460                 spin_lock(&cifs_sb->tlink_tree_lock);
4461                 /* was one inserted after previous search? */
4462                 tlink = tlink_rb_search(&cifs_sb->tlink_tree, fsuid);
4463                 if (tlink) {
4464                         cifs_get_tlink(tlink);
4465                         spin_unlock(&cifs_sb->tlink_tree_lock);
4466                         kfree(newtlink);
4467                         goto wait_for_construction;
4468                 }
4469                 tlink = newtlink;
4470                 tlink_rb_insert(&cifs_sb->tlink_tree, tlink);
4471                 spin_unlock(&cifs_sb->tlink_tree_lock);
4472         } else {
4473 wait_for_construction:
4474                 ret = wait_on_bit(&tlink->tl_flags, TCON_LINK_PENDING,
4475                                   TASK_INTERRUPTIBLE);
4476                 if (ret) {
4477                         cifs_put_tlink(tlink);
4478                         return ERR_PTR(-ERESTARTSYS);
4479                 }
4480
4481                 /* if it's good, return it */
4482                 if (!IS_ERR(tlink->tl_tcon))
4483                         return tlink;
4484
4485                 /* return error if we tried this already recently */
4486                 if (time_before(jiffies, tlink->tl_time + TLINK_ERROR_EXPIRE)) {
4487                         cifs_put_tlink(tlink);
4488                         return ERR_PTR(-EACCES);
4489                 }
4490
4491                 if (test_and_set_bit(TCON_LINK_PENDING, &tlink->tl_flags))
4492                         goto wait_for_construction;
4493         }
4494
4495         tlink->tl_tcon = cifs_construct_tcon(cifs_sb, fsuid);
4496         clear_bit(TCON_LINK_PENDING, &tlink->tl_flags);
4497         wake_up_bit(&tlink->tl_flags, TCON_LINK_PENDING);
4498
4499         if (IS_ERR(tlink->tl_tcon)) {
4500                 cifs_put_tlink(tlink);
4501                 return ERR_PTR(-EACCES);
4502         }
4503
4504         return tlink;
4505 }
4506
4507 /*
4508  * periodic workqueue job that scans tcon_tree for a superblock and closes
4509  * out tcons.
4510  */
4511 static void
4512 cifs_prune_tlinks(struct work_struct *work)
4513 {
4514         struct cifs_sb_info *cifs_sb = container_of(work, struct cifs_sb_info,
4515                                                     prune_tlinks.work);
4516         struct rb_root *root = &cifs_sb->tlink_tree;
4517         struct rb_node *node = rb_first(root);
4518         struct rb_node *tmp;
4519         struct tcon_link *tlink;
4520
4521         /*
4522          * Because we drop the spinlock in the loop in order to put the tlink
4523          * it's not guarded against removal of links from the tree. The only
4524          * places that remove entries from the tree are this function and
4525          * umounts. Because this function is non-reentrant and is canceled
4526          * before umount can proceed, this is safe.
4527          */
4528         spin_lock(&cifs_sb->tlink_tree_lock);
4529         node = rb_first(root);
4530         while (node != NULL) {
4531                 tmp = node;
4532                 node = rb_next(tmp);
4533                 tlink = rb_entry(tmp, struct tcon_link, tl_rbnode);
4534
4535                 if (test_bit(TCON_LINK_MASTER, &tlink->tl_flags) ||
4536                     atomic_read(&tlink->tl_count) != 0 ||
4537                     time_after(tlink->tl_time + TLINK_IDLE_EXPIRE, jiffies))
4538                         continue;
4539
4540                 cifs_get_tlink(tlink);
4541                 clear_bit(TCON_LINK_IN_TREE, &tlink->tl_flags);
4542                 rb_erase(tmp, root);
4543
4544                 spin_unlock(&cifs_sb->tlink_tree_lock);
4545                 cifs_put_tlink(tlink);
4546                 spin_lock(&cifs_sb->tlink_tree_lock);
4547         }
4548         spin_unlock(&cifs_sb->tlink_tree_lock);
4549
4550         queue_delayed_work(cifsiod_wq, &cifs_sb->prune_tlinks,
4551                                 TLINK_IDLE_EXPIRE);
4552 }