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