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