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