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