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