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