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