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