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