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