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