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