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