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