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