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