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