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