smb: client: instantiate when creating SFU files
[sfrench/cifs-2.6.git] / fs / smb / client / misc.c
1 // SPDX-License-Identifier: LGPL-2.1
2 /*
3  *
4  *   Copyright (C) International Business Machines  Corp., 2002,2008
5  *   Author(s): Steve French (sfrench@us.ibm.com)
6  *
7  */
8
9 #include <linux/slab.h>
10 #include <linux/ctype.h>
11 #include <linux/mempool.h>
12 #include <linux/vmalloc.h>
13 #include "cifspdu.h"
14 #include "cifsglob.h"
15 #include "cifsproto.h"
16 #include "cifs_debug.h"
17 #include "smberr.h"
18 #include "nterr.h"
19 #include "cifs_unicode.h"
20 #include "smb2pdu.h"
21 #include "cifsfs.h"
22 #ifdef CONFIG_CIFS_DFS_UPCALL
23 #include "dns_resolve.h"
24 #include "dfs_cache.h"
25 #include "dfs.h"
26 #endif
27 #include "fs_context.h"
28 #include "cached_dir.h"
29
30 /* The xid serves as a useful identifier for each incoming vfs request,
31    in a similar way to the mid which is useful to track each sent smb,
32    and CurrentXid can also provide a running counter (although it
33    will eventually wrap past zero) of the total vfs operations handled
34    since the cifs fs was mounted */
35
36 unsigned int
37 _get_xid(void)
38 {
39         unsigned int xid;
40
41         spin_lock(&GlobalMid_Lock);
42         GlobalTotalActiveXid++;
43
44         /* keep high water mark for number of simultaneous ops in filesystem */
45         if (GlobalTotalActiveXid > GlobalMaxActiveXid)
46                 GlobalMaxActiveXid = GlobalTotalActiveXid;
47         if (GlobalTotalActiveXid > 65000)
48                 cifs_dbg(FYI, "warning: more than 65000 requests active\n");
49         xid = GlobalCurrentXid++;
50         spin_unlock(&GlobalMid_Lock);
51         return xid;
52 }
53
54 void
55 _free_xid(unsigned int xid)
56 {
57         spin_lock(&GlobalMid_Lock);
58         /* if (GlobalTotalActiveXid == 0)
59                 BUG(); */
60         GlobalTotalActiveXid--;
61         spin_unlock(&GlobalMid_Lock);
62 }
63
64 struct cifs_ses *
65 sesInfoAlloc(void)
66 {
67         struct cifs_ses *ret_buf;
68
69         ret_buf = kzalloc(sizeof(struct cifs_ses), GFP_KERNEL);
70         if (ret_buf) {
71                 atomic_inc(&sesInfoAllocCount);
72                 spin_lock_init(&ret_buf->ses_lock);
73                 ret_buf->ses_status = SES_NEW;
74                 ++ret_buf->ses_count;
75                 INIT_LIST_HEAD(&ret_buf->smb_ses_list);
76                 INIT_LIST_HEAD(&ret_buf->tcon_list);
77                 mutex_init(&ret_buf->session_mutex);
78                 spin_lock_init(&ret_buf->iface_lock);
79                 INIT_LIST_HEAD(&ret_buf->iface_list);
80                 spin_lock_init(&ret_buf->chan_lock);
81         }
82         return ret_buf;
83 }
84
85 void
86 sesInfoFree(struct cifs_ses *buf_to_free)
87 {
88         struct cifs_server_iface *iface = NULL, *niface = NULL;
89
90         if (buf_to_free == NULL) {
91                 cifs_dbg(FYI, "Null buffer passed to sesInfoFree\n");
92                 return;
93         }
94
95         unload_nls(buf_to_free->local_nls);
96         atomic_dec(&sesInfoAllocCount);
97         kfree(buf_to_free->serverOS);
98         kfree(buf_to_free->serverDomain);
99         kfree(buf_to_free->serverNOS);
100         kfree_sensitive(buf_to_free->password);
101         kfree(buf_to_free->user_name);
102         kfree(buf_to_free->domainName);
103         kfree_sensitive(buf_to_free->auth_key.response);
104         spin_lock(&buf_to_free->iface_lock);
105         list_for_each_entry_safe(iface, niface, &buf_to_free->iface_list,
106                                  iface_head)
107                 kref_put(&iface->refcount, release_iface);
108         spin_unlock(&buf_to_free->iface_lock);
109         kfree_sensitive(buf_to_free);
110 }
111
112 struct cifs_tcon *
113 tcon_info_alloc(bool dir_leases_enabled)
114 {
115         struct cifs_tcon *ret_buf;
116
117         ret_buf = kzalloc(sizeof(*ret_buf), GFP_KERNEL);
118         if (!ret_buf)
119                 return NULL;
120
121         if (dir_leases_enabled == true) {
122                 ret_buf->cfids = init_cached_dirs();
123                 if (!ret_buf->cfids) {
124                         kfree(ret_buf);
125                         return NULL;
126                 }
127         }
128         /* else ret_buf->cfids is already set to NULL above */
129
130         atomic_inc(&tconInfoAllocCount);
131         ret_buf->status = TID_NEW;
132         ++ret_buf->tc_count;
133         spin_lock_init(&ret_buf->tc_lock);
134         INIT_LIST_HEAD(&ret_buf->openFileList);
135         INIT_LIST_HEAD(&ret_buf->tcon_list);
136         spin_lock_init(&ret_buf->open_file_lock);
137         spin_lock_init(&ret_buf->stat_lock);
138         atomic_set(&ret_buf->num_local_opens, 0);
139         atomic_set(&ret_buf->num_remote_opens, 0);
140         ret_buf->stats_from_time = ktime_get_real_seconds();
141
142         return ret_buf;
143 }
144
145 void
146 tconInfoFree(struct cifs_tcon *tcon)
147 {
148         if (tcon == NULL) {
149                 cifs_dbg(FYI, "Null buffer passed to tconInfoFree\n");
150                 return;
151         }
152         free_cached_dirs(tcon->cfids);
153         atomic_dec(&tconInfoAllocCount);
154         kfree(tcon->nativeFileSystem);
155         kfree_sensitive(tcon->password);
156         kfree(tcon->origin_fullpath);
157         kfree(tcon);
158 }
159
160 struct smb_hdr *
161 cifs_buf_get(void)
162 {
163         struct smb_hdr *ret_buf = NULL;
164         /*
165          * SMB2 header is bigger than CIFS one - no problems to clean some
166          * more bytes for CIFS.
167          */
168         size_t buf_size = sizeof(struct smb2_hdr);
169
170         /*
171          * We could use negotiated size instead of max_msgsize -
172          * but it may be more efficient to always alloc same size
173          * albeit slightly larger than necessary and maxbuffersize
174          * defaults to this and can not be bigger.
175          */
176         ret_buf = mempool_alloc(cifs_req_poolp, GFP_NOFS);
177
178         /* clear the first few header bytes */
179         /* for most paths, more is cleared in header_assemble */
180         memset(ret_buf, 0, buf_size + 3);
181         atomic_inc(&buf_alloc_count);
182 #ifdef CONFIG_CIFS_STATS2
183         atomic_inc(&total_buf_alloc_count);
184 #endif /* CONFIG_CIFS_STATS2 */
185
186         return ret_buf;
187 }
188
189 void
190 cifs_buf_release(void *buf_to_free)
191 {
192         if (buf_to_free == NULL) {
193                 /* cifs_dbg(FYI, "Null buffer passed to cifs_buf_release\n");*/
194                 return;
195         }
196         mempool_free(buf_to_free, cifs_req_poolp);
197
198         atomic_dec(&buf_alloc_count);
199         return;
200 }
201
202 struct smb_hdr *
203 cifs_small_buf_get(void)
204 {
205         struct smb_hdr *ret_buf = NULL;
206
207 /* We could use negotiated size instead of max_msgsize -
208    but it may be more efficient to always alloc same size
209    albeit slightly larger than necessary and maxbuffersize
210    defaults to this and can not be bigger */
211         ret_buf = mempool_alloc(cifs_sm_req_poolp, GFP_NOFS);
212         /* No need to clear memory here, cleared in header assemble */
213         /*      memset(ret_buf, 0, sizeof(struct smb_hdr) + 27);*/
214         atomic_inc(&small_buf_alloc_count);
215 #ifdef CONFIG_CIFS_STATS2
216         atomic_inc(&total_small_buf_alloc_count);
217 #endif /* CONFIG_CIFS_STATS2 */
218
219         return ret_buf;
220 }
221
222 void
223 cifs_small_buf_release(void *buf_to_free)
224 {
225
226         if (buf_to_free == NULL) {
227                 cifs_dbg(FYI, "Null buffer passed to cifs_small_buf_release\n");
228                 return;
229         }
230         mempool_free(buf_to_free, cifs_sm_req_poolp);
231
232         atomic_dec(&small_buf_alloc_count);
233         return;
234 }
235
236 void
237 free_rsp_buf(int resp_buftype, void *rsp)
238 {
239         if (resp_buftype == CIFS_SMALL_BUFFER)
240                 cifs_small_buf_release(rsp);
241         else if (resp_buftype == CIFS_LARGE_BUFFER)
242                 cifs_buf_release(rsp);
243 }
244
245 /* NB: MID can not be set if treeCon not passed in, in that
246    case it is responsbility of caller to set the mid */
247 void
248 header_assemble(struct smb_hdr *buffer, char smb_command /* command */ ,
249                 const struct cifs_tcon *treeCon, int word_count
250                 /* length of fixed section (word count) in two byte units  */)
251 {
252         char *temp = (char *) buffer;
253
254         memset(temp, 0, 256); /* bigger than MAX_CIFS_HDR_SIZE */
255
256         buffer->smb_buf_length = cpu_to_be32(
257             (2 * word_count) + sizeof(struct smb_hdr) -
258             4 /*  RFC 1001 length field does not count */  +
259             2 /* for bcc field itself */) ;
260
261         buffer->Protocol[0] = 0xFF;
262         buffer->Protocol[1] = 'S';
263         buffer->Protocol[2] = 'M';
264         buffer->Protocol[3] = 'B';
265         buffer->Command = smb_command;
266         buffer->Flags = 0x00;   /* case sensitive */
267         buffer->Flags2 = SMBFLG2_KNOWS_LONG_NAMES;
268         buffer->Pid = cpu_to_le16((__u16)current->tgid);
269         buffer->PidHigh = cpu_to_le16((__u16)(current->tgid >> 16));
270         if (treeCon) {
271                 buffer->Tid = treeCon->tid;
272                 if (treeCon->ses) {
273                         if (treeCon->ses->capabilities & CAP_UNICODE)
274                                 buffer->Flags2 |= SMBFLG2_UNICODE;
275                         if (treeCon->ses->capabilities & CAP_STATUS32)
276                                 buffer->Flags2 |= SMBFLG2_ERR_STATUS;
277
278                         /* Uid is not converted */
279                         buffer->Uid = treeCon->ses->Suid;
280                         if (treeCon->ses->server)
281                                 buffer->Mid = get_next_mid(treeCon->ses->server);
282                 }
283                 if (treeCon->Flags & SMB_SHARE_IS_IN_DFS)
284                         buffer->Flags2 |= SMBFLG2_DFS;
285                 if (treeCon->nocase)
286                         buffer->Flags  |= SMBFLG_CASELESS;
287                 if ((treeCon->ses) && (treeCon->ses->server))
288                         if (treeCon->ses->server->sign)
289                                 buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE;
290         }
291
292 /*  endian conversion of flags is now done just before sending */
293         buffer->WordCount = (char) word_count;
294         return;
295 }
296
297 static int
298 check_smb_hdr(struct smb_hdr *smb)
299 {
300         /* does it have the right SMB "signature" ? */
301         if (*(__le32 *) smb->Protocol != cpu_to_le32(0x424d53ff)) {
302                 cifs_dbg(VFS, "Bad protocol string signature header 0x%x\n",
303                          *(unsigned int *)smb->Protocol);
304                 return 1;
305         }
306
307         /* if it's a response then accept */
308         if (smb->Flags & SMBFLG_RESPONSE)
309                 return 0;
310
311         /* only one valid case where server sends us request */
312         if (smb->Command == SMB_COM_LOCKING_ANDX)
313                 return 0;
314
315         cifs_dbg(VFS, "Server sent request, not response. mid=%u\n",
316                  get_mid(smb));
317         return 1;
318 }
319
320 int
321 checkSMB(char *buf, unsigned int total_read, struct TCP_Server_Info *server)
322 {
323         struct smb_hdr *smb = (struct smb_hdr *)buf;
324         __u32 rfclen = be32_to_cpu(smb->smb_buf_length);
325         __u32 clc_len;  /* calculated length */
326         cifs_dbg(FYI, "checkSMB Length: 0x%x, smb_buf_length: 0x%x\n",
327                  total_read, rfclen);
328
329         /* is this frame too small to even get to a BCC? */
330         if (total_read < 2 + sizeof(struct smb_hdr)) {
331                 if ((total_read >= sizeof(struct smb_hdr) - 1)
332                             && (smb->Status.CifsError != 0)) {
333                         /* it's an error return */
334                         smb->WordCount = 0;
335                         /* some error cases do not return wct and bcc */
336                         return 0;
337                 } else if ((total_read == sizeof(struct smb_hdr) + 1) &&
338                                 (smb->WordCount == 0)) {
339                         char *tmp = (char *)smb;
340                         /* Need to work around a bug in two servers here */
341                         /* First, check if the part of bcc they sent was zero */
342                         if (tmp[sizeof(struct smb_hdr)] == 0) {
343                                 /* some servers return only half of bcc
344                                  * on simple responses (wct, bcc both zero)
345                                  * in particular have seen this on
346                                  * ulogoffX and FindClose. This leaves
347                                  * one byte of bcc potentially unitialized
348                                  */
349                                 /* zero rest of bcc */
350                                 tmp[sizeof(struct smb_hdr)+1] = 0;
351                                 return 0;
352                         }
353                         cifs_dbg(VFS, "rcvd invalid byte count (bcc)\n");
354                 } else {
355                         cifs_dbg(VFS, "Length less than smb header size\n");
356                 }
357                 return -EIO;
358         } else if (total_read < sizeof(*smb) + 2 * smb->WordCount) {
359                 cifs_dbg(VFS, "%s: can't read BCC due to invalid WordCount(%u)\n",
360                          __func__, smb->WordCount);
361                 return -EIO;
362         }
363
364         /* otherwise, there is enough to get to the BCC */
365         if (check_smb_hdr(smb))
366                 return -EIO;
367         clc_len = smbCalcSize(smb);
368
369         if (4 + rfclen != total_read) {
370                 cifs_dbg(VFS, "Length read does not match RFC1001 length %d\n",
371                          rfclen);
372                 return -EIO;
373         }
374
375         if (4 + rfclen != clc_len) {
376                 __u16 mid = get_mid(smb);
377                 /* check if bcc wrapped around for large read responses */
378                 if ((rfclen > 64 * 1024) && (rfclen > clc_len)) {
379                         /* check if lengths match mod 64K */
380                         if (((4 + rfclen) & 0xFFFF) == (clc_len & 0xFFFF))
381                                 return 0; /* bcc wrapped */
382                 }
383                 cifs_dbg(FYI, "Calculated size %u vs length %u mismatch for mid=%u\n",
384                          clc_len, 4 + rfclen, mid);
385
386                 if (4 + rfclen < clc_len) {
387                         cifs_dbg(VFS, "RFC1001 size %u smaller than SMB for mid=%u\n",
388                                  rfclen, mid);
389                         return -EIO;
390                 } else if (rfclen > clc_len + 512) {
391                         /*
392                          * Some servers (Windows XP in particular) send more
393                          * data than the lengths in the SMB packet would
394                          * indicate on certain calls (byte range locks and
395                          * trans2 find first calls in particular). While the
396                          * client can handle such a frame by ignoring the
397                          * trailing data, we choose limit the amount of extra
398                          * data to 512 bytes.
399                          */
400                         cifs_dbg(VFS, "RFC1001 size %u more than 512 bytes larger than SMB for mid=%u\n",
401                                  rfclen, mid);
402                         return -EIO;
403                 }
404         }
405         return 0;
406 }
407
408 bool
409 is_valid_oplock_break(char *buffer, struct TCP_Server_Info *srv)
410 {
411         struct smb_hdr *buf = (struct smb_hdr *)buffer;
412         struct smb_com_lock_req *pSMB = (struct smb_com_lock_req *)buf;
413         struct TCP_Server_Info *pserver;
414         struct cifs_ses *ses;
415         struct cifs_tcon *tcon;
416         struct cifsInodeInfo *pCifsInode;
417         struct cifsFileInfo *netfile;
418
419         cifs_dbg(FYI, "Checking for oplock break or dnotify response\n");
420         if ((pSMB->hdr.Command == SMB_COM_NT_TRANSACT) &&
421            (pSMB->hdr.Flags & SMBFLG_RESPONSE)) {
422                 struct smb_com_transaction_change_notify_rsp *pSMBr =
423                         (struct smb_com_transaction_change_notify_rsp *)buf;
424                 struct file_notify_information *pnotify;
425                 __u32 data_offset = 0;
426                 size_t len = srv->total_read - sizeof(pSMBr->hdr.smb_buf_length);
427
428                 if (get_bcc(buf) > sizeof(struct file_notify_information)) {
429                         data_offset = le32_to_cpu(pSMBr->DataOffset);
430
431                         if (data_offset >
432                             len - sizeof(struct file_notify_information)) {
433                                 cifs_dbg(FYI, "Invalid data_offset %u\n",
434                                          data_offset);
435                                 return true;
436                         }
437                         pnotify = (struct file_notify_information *)
438                                 ((char *)&pSMBr->hdr.Protocol + data_offset);
439                         cifs_dbg(FYI, "dnotify on %s Action: 0x%x\n",
440                                  pnotify->FileName, pnotify->Action);
441                         /*   cifs_dump_mem("Rcvd notify Data: ",buf,
442                                 sizeof(struct smb_hdr)+60); */
443                         return true;
444                 }
445                 if (pSMBr->hdr.Status.CifsError) {
446                         cifs_dbg(FYI, "notify err 0x%x\n",
447                                  pSMBr->hdr.Status.CifsError);
448                         return true;
449                 }
450                 return false;
451         }
452         if (pSMB->hdr.Command != SMB_COM_LOCKING_ANDX)
453                 return false;
454         if (pSMB->hdr.Flags & SMBFLG_RESPONSE) {
455                 /* no sense logging error on invalid handle on oplock
456                    break - harmless race between close request and oplock
457                    break response is expected from time to time writing out
458                    large dirty files cached on the client */
459                 if ((NT_STATUS_INVALID_HANDLE) ==
460                    le32_to_cpu(pSMB->hdr.Status.CifsError)) {
461                         cifs_dbg(FYI, "Invalid handle on oplock break\n");
462                         return true;
463                 } else if (ERRbadfid ==
464                    le16_to_cpu(pSMB->hdr.Status.DosError.Error)) {
465                         return true;
466                 } else {
467                         return false; /* on valid oplock brk we get "request" */
468                 }
469         }
470         if (pSMB->hdr.WordCount != 8)
471                 return false;
472
473         cifs_dbg(FYI, "oplock type 0x%x level 0x%x\n",
474                  pSMB->LockType, pSMB->OplockLevel);
475         if (!(pSMB->LockType & LOCKING_ANDX_OPLOCK_RELEASE))
476                 return false;
477
478         /* If server is a channel, select the primary channel */
479         pserver = SERVER_IS_CHAN(srv) ? srv->primary_server : srv;
480
481         /* look up tcon based on tid & uid */
482         spin_lock(&cifs_tcp_ses_lock);
483         list_for_each_entry(ses, &pserver->smb_ses_list, smb_ses_list) {
484                 if (cifs_ses_exiting(ses))
485                         continue;
486                 list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
487                         if (tcon->tid != buf->Tid)
488                                 continue;
489
490                         cifs_stats_inc(&tcon->stats.cifs_stats.num_oplock_brks);
491                         spin_lock(&tcon->open_file_lock);
492                         list_for_each_entry(netfile, &tcon->openFileList, tlist) {
493                                 if (pSMB->Fid != netfile->fid.netfid)
494                                         continue;
495
496                                 cifs_dbg(FYI, "file id match, oplock break\n");
497                                 pCifsInode = CIFS_I(d_inode(netfile->dentry));
498
499                                 set_bit(CIFS_INODE_PENDING_OPLOCK_BREAK,
500                                         &pCifsInode->flags);
501
502                                 netfile->oplock_epoch = 0;
503                                 netfile->oplock_level = pSMB->OplockLevel;
504                                 netfile->oplock_break_cancelled = false;
505                                 cifs_queue_oplock_break(netfile);
506
507                                 spin_unlock(&tcon->open_file_lock);
508                                 spin_unlock(&cifs_tcp_ses_lock);
509                                 return true;
510                         }
511                         spin_unlock(&tcon->open_file_lock);
512                         spin_unlock(&cifs_tcp_ses_lock);
513                         cifs_dbg(FYI, "No matching file for oplock break\n");
514                         return true;
515                 }
516         }
517         spin_unlock(&cifs_tcp_ses_lock);
518         cifs_dbg(FYI, "Can not process oplock break for non-existent connection\n");
519         return true;
520 }
521
522 void
523 dump_smb(void *buf, int smb_buf_length)
524 {
525         if (traceSMB == 0)
526                 return;
527
528         print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_NONE, 8, 2, buf,
529                        smb_buf_length, true);
530 }
531
532 void
533 cifs_autodisable_serverino(struct cifs_sb_info *cifs_sb)
534 {
535         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
536                 struct cifs_tcon *tcon = NULL;
537
538                 if (cifs_sb->master_tlink)
539                         tcon = cifs_sb_master_tcon(cifs_sb);
540
541                 cifs_sb->mnt_cifs_flags &= ~CIFS_MOUNT_SERVER_INUM;
542                 cifs_sb->mnt_cifs_serverino_autodisabled = true;
543                 cifs_dbg(VFS, "Autodisabling the use of server inode numbers on %s\n",
544                          tcon ? tcon->tree_name : "new server");
545                 cifs_dbg(VFS, "The server doesn't seem to support them properly or the files might be on different servers (DFS)\n");
546                 cifs_dbg(VFS, "Hardlinks will not be recognized on this mount. Consider mounting with the \"noserverino\" option to silence this message.\n");
547
548         }
549 }
550
551 void cifs_set_oplock_level(struct cifsInodeInfo *cinode, __u32 oplock)
552 {
553         oplock &= 0xF;
554
555         if (oplock == OPLOCK_EXCLUSIVE) {
556                 cinode->oplock = CIFS_CACHE_WRITE_FLG | CIFS_CACHE_READ_FLG;
557                 cifs_dbg(FYI, "Exclusive Oplock granted on inode %p\n",
558                          &cinode->netfs.inode);
559         } else if (oplock == OPLOCK_READ) {
560                 cinode->oplock = CIFS_CACHE_READ_FLG;
561                 cifs_dbg(FYI, "Level II Oplock granted on inode %p\n",
562                          &cinode->netfs.inode);
563         } else
564                 cinode->oplock = 0;
565 }
566
567 /*
568  * We wait for oplock breaks to be processed before we attempt to perform
569  * writes.
570  */
571 int cifs_get_writer(struct cifsInodeInfo *cinode)
572 {
573         int rc;
574
575 start:
576         rc = wait_on_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK,
577                          TASK_KILLABLE);
578         if (rc)
579                 return rc;
580
581         spin_lock(&cinode->writers_lock);
582         if (!cinode->writers)
583                 set_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
584         cinode->writers++;
585         /* Check to see if we have started servicing an oplock break */
586         if (test_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags)) {
587                 cinode->writers--;
588                 if (cinode->writers == 0) {
589                         clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
590                         wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
591                 }
592                 spin_unlock(&cinode->writers_lock);
593                 goto start;
594         }
595         spin_unlock(&cinode->writers_lock);
596         return 0;
597 }
598
599 void cifs_put_writer(struct cifsInodeInfo *cinode)
600 {
601         spin_lock(&cinode->writers_lock);
602         cinode->writers--;
603         if (cinode->writers == 0) {
604                 clear_bit(CIFS_INODE_PENDING_WRITERS, &cinode->flags);
605                 wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_WRITERS);
606         }
607         spin_unlock(&cinode->writers_lock);
608 }
609
610 /**
611  * cifs_queue_oplock_break - queue the oplock break handler for cfile
612  * @cfile: The file to break the oplock on
613  *
614  * This function is called from the demultiplex thread when it
615  * receives an oplock break for @cfile.
616  *
617  * Assumes the tcon->open_file_lock is held.
618  * Assumes cfile->file_info_lock is NOT held.
619  */
620 void cifs_queue_oplock_break(struct cifsFileInfo *cfile)
621 {
622         /*
623          * Bump the handle refcount now while we hold the
624          * open_file_lock to enforce the validity of it for the oplock
625          * break handler. The matching put is done at the end of the
626          * handler.
627          */
628         cifsFileInfo_get(cfile);
629
630         queue_work(cifsoplockd_wq, &cfile->oplock_break);
631 }
632
633 void cifs_done_oplock_break(struct cifsInodeInfo *cinode)
634 {
635         clear_bit(CIFS_INODE_PENDING_OPLOCK_BREAK, &cinode->flags);
636         wake_up_bit(&cinode->flags, CIFS_INODE_PENDING_OPLOCK_BREAK);
637 }
638
639 bool
640 backup_cred(struct cifs_sb_info *cifs_sb)
641 {
642         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPUID) {
643                 if (uid_eq(cifs_sb->ctx->backupuid, current_fsuid()))
644                         return true;
645         }
646         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_BACKUPGID) {
647                 if (in_group_p(cifs_sb->ctx->backupgid))
648                         return true;
649         }
650
651         return false;
652 }
653
654 void
655 cifs_del_pending_open(struct cifs_pending_open *open)
656 {
657         spin_lock(&tlink_tcon(open->tlink)->open_file_lock);
658         list_del(&open->olist);
659         spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
660 }
661
662 void
663 cifs_add_pending_open_locked(struct cifs_fid *fid, struct tcon_link *tlink,
664                              struct cifs_pending_open *open)
665 {
666         memcpy(open->lease_key, fid->lease_key, SMB2_LEASE_KEY_SIZE);
667         open->oplock = CIFS_OPLOCK_NO_CHANGE;
668         open->tlink = tlink;
669         fid->pending_open = open;
670         list_add_tail(&open->olist, &tlink_tcon(tlink)->pending_opens);
671 }
672
673 void
674 cifs_add_pending_open(struct cifs_fid *fid, struct tcon_link *tlink,
675                       struct cifs_pending_open *open)
676 {
677         spin_lock(&tlink_tcon(tlink)->open_file_lock);
678         cifs_add_pending_open_locked(fid, tlink, open);
679         spin_unlock(&tlink_tcon(open->tlink)->open_file_lock);
680 }
681
682 /*
683  * Critical section which runs after acquiring deferred_lock.
684  * As there is no reference count on cifs_deferred_close, pdclose
685  * should not be used outside deferred_lock.
686  */
687 bool
688 cifs_is_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close **pdclose)
689 {
690         struct cifs_deferred_close *dclose;
691
692         list_for_each_entry(dclose, &CIFS_I(d_inode(cfile->dentry))->deferred_closes, dlist) {
693                 if ((dclose->netfid == cfile->fid.netfid) &&
694                         (dclose->persistent_fid == cfile->fid.persistent_fid) &&
695                         (dclose->volatile_fid == cfile->fid.volatile_fid)) {
696                         *pdclose = dclose;
697                         return true;
698                 }
699         }
700         return false;
701 }
702
703 /*
704  * Critical section which runs after acquiring deferred_lock.
705  */
706 void
707 cifs_add_deferred_close(struct cifsFileInfo *cfile, struct cifs_deferred_close *dclose)
708 {
709         bool is_deferred = false;
710         struct cifs_deferred_close *pdclose;
711
712         is_deferred = cifs_is_deferred_close(cfile, &pdclose);
713         if (is_deferred) {
714                 kfree(dclose);
715                 return;
716         }
717
718         dclose->tlink = cfile->tlink;
719         dclose->netfid = cfile->fid.netfid;
720         dclose->persistent_fid = cfile->fid.persistent_fid;
721         dclose->volatile_fid = cfile->fid.volatile_fid;
722         list_add_tail(&dclose->dlist, &CIFS_I(d_inode(cfile->dentry))->deferred_closes);
723 }
724
725 /*
726  * Critical section which runs after acquiring deferred_lock.
727  */
728 void
729 cifs_del_deferred_close(struct cifsFileInfo *cfile)
730 {
731         bool is_deferred = false;
732         struct cifs_deferred_close *dclose;
733
734         is_deferred = cifs_is_deferred_close(cfile, &dclose);
735         if (!is_deferred)
736                 return;
737         list_del(&dclose->dlist);
738         kfree(dclose);
739 }
740
741 void
742 cifs_close_deferred_file(struct cifsInodeInfo *cifs_inode)
743 {
744         struct cifsFileInfo *cfile = NULL;
745         struct file_list *tmp_list, *tmp_next_list;
746         struct list_head file_head;
747
748         if (cifs_inode == NULL)
749                 return;
750
751         INIT_LIST_HEAD(&file_head);
752         spin_lock(&cifs_inode->open_file_lock);
753         list_for_each_entry(cfile, &cifs_inode->openFileList, flist) {
754                 if (delayed_work_pending(&cfile->deferred)) {
755                         if (cancel_delayed_work(&cfile->deferred)) {
756                                 spin_lock(&cifs_inode->deferred_lock);
757                                 cifs_del_deferred_close(cfile);
758                                 spin_unlock(&cifs_inode->deferred_lock);
759
760                                 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
761                                 if (tmp_list == NULL)
762                                         break;
763                                 tmp_list->cfile = cfile;
764                                 list_add_tail(&tmp_list->list, &file_head);
765                         }
766                 }
767         }
768         spin_unlock(&cifs_inode->open_file_lock);
769
770         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
771                 _cifsFileInfo_put(tmp_list->cfile, false, false);
772                 list_del(&tmp_list->list);
773                 kfree(tmp_list);
774         }
775 }
776
777 void
778 cifs_close_all_deferred_files(struct cifs_tcon *tcon)
779 {
780         struct cifsFileInfo *cfile;
781         struct file_list *tmp_list, *tmp_next_list;
782         struct list_head file_head;
783
784         INIT_LIST_HEAD(&file_head);
785         spin_lock(&tcon->open_file_lock);
786         list_for_each_entry(cfile, &tcon->openFileList, tlist) {
787                 if (delayed_work_pending(&cfile->deferred)) {
788                         if (cancel_delayed_work(&cfile->deferred)) {
789                                 spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
790                                 cifs_del_deferred_close(cfile);
791                                 spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
792
793                                 tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
794                                 if (tmp_list == NULL)
795                                         break;
796                                 tmp_list->cfile = cfile;
797                                 list_add_tail(&tmp_list->list, &file_head);
798                         }
799                 }
800         }
801         spin_unlock(&tcon->open_file_lock);
802
803         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
804                 _cifsFileInfo_put(tmp_list->cfile, true, false);
805                 list_del(&tmp_list->list);
806                 kfree(tmp_list);
807         }
808 }
809 void
810 cifs_close_deferred_file_under_dentry(struct cifs_tcon *tcon, const char *path)
811 {
812         struct cifsFileInfo *cfile;
813         struct file_list *tmp_list, *tmp_next_list;
814         struct list_head file_head;
815         void *page;
816         const char *full_path;
817
818         INIT_LIST_HEAD(&file_head);
819         page = alloc_dentry_path();
820         spin_lock(&tcon->open_file_lock);
821         list_for_each_entry(cfile, &tcon->openFileList, tlist) {
822                 full_path = build_path_from_dentry(cfile->dentry, page);
823                 if (strstr(full_path, path)) {
824                         if (delayed_work_pending(&cfile->deferred)) {
825                                 if (cancel_delayed_work(&cfile->deferred)) {
826                                         spin_lock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
827                                         cifs_del_deferred_close(cfile);
828                                         spin_unlock(&CIFS_I(d_inode(cfile->dentry))->deferred_lock);
829
830                                         tmp_list = kmalloc(sizeof(struct file_list), GFP_ATOMIC);
831                                         if (tmp_list == NULL)
832                                                 break;
833                                         tmp_list->cfile = cfile;
834                                         list_add_tail(&tmp_list->list, &file_head);
835                                 }
836                         }
837                 }
838         }
839         spin_unlock(&tcon->open_file_lock);
840
841         list_for_each_entry_safe(tmp_list, tmp_next_list, &file_head, list) {
842                 _cifsFileInfo_put(tmp_list->cfile, true, false);
843                 list_del(&tmp_list->list);
844                 kfree(tmp_list);
845         }
846         free_dentry_path(page);
847 }
848
849 /*
850  * If a dentry has been deleted, all corresponding open handles should know that
851  * so that we do not defer close them.
852  */
853 void cifs_mark_open_handles_for_deleted_file(struct inode *inode,
854                                              const char *path)
855 {
856         struct cifsFileInfo *cfile;
857         void *page;
858         const char *full_path;
859         struct cifsInodeInfo *cinode = CIFS_I(inode);
860
861         page = alloc_dentry_path();
862         spin_lock(&cinode->open_file_lock);
863
864         /*
865          * note: we need to construct path from dentry and compare only if the
866          * inode has any hardlinks. When number of hardlinks is 1, we can just
867          * mark all open handles since they are going to be from the same file.
868          */
869         if (inode->i_nlink > 1) {
870                 list_for_each_entry(cfile, &cinode->openFileList, flist) {
871                         full_path = build_path_from_dentry(cfile->dentry, page);
872                         if (!IS_ERR(full_path) && strcmp(full_path, path) == 0)
873                                 cfile->status_file_deleted = true;
874                 }
875         } else {
876                 list_for_each_entry(cfile, &cinode->openFileList, flist)
877                         cfile->status_file_deleted = true;
878         }
879         spin_unlock(&cinode->open_file_lock);
880         free_dentry_path(page);
881 }
882
883 /* parses DFS referral V3 structure
884  * caller is responsible for freeing target_nodes
885  * returns:
886  * - on success - 0
887  * - on failure - errno
888  */
889 int
890 parse_dfs_referrals(struct get_dfs_referral_rsp *rsp, u32 rsp_size,
891                     unsigned int *num_of_nodes,
892                     struct dfs_info3_param **target_nodes,
893                     const struct nls_table *nls_codepage, int remap,
894                     const char *searchName, bool is_unicode)
895 {
896         int i, rc = 0;
897         char *data_end;
898         struct dfs_referral_level_3 *ref;
899
900         *num_of_nodes = le16_to_cpu(rsp->NumberOfReferrals);
901
902         if (*num_of_nodes < 1) {
903                 cifs_dbg(VFS, "num_referrals: must be at least > 0, but we get num_referrals = %d\n",
904                          *num_of_nodes);
905                 rc = -EINVAL;
906                 goto parse_DFS_referrals_exit;
907         }
908
909         ref = (struct dfs_referral_level_3 *) &(rsp->referrals);
910         if (ref->VersionNumber != cpu_to_le16(3)) {
911                 cifs_dbg(VFS, "Referrals of V%d version are not supported, should be V3\n",
912                          le16_to_cpu(ref->VersionNumber));
913                 rc = -EINVAL;
914                 goto parse_DFS_referrals_exit;
915         }
916
917         /* get the upper boundary of the resp buffer */
918         data_end = (char *)rsp + rsp_size;
919
920         cifs_dbg(FYI, "num_referrals: %d dfs flags: 0x%x ...\n",
921                  *num_of_nodes, le32_to_cpu(rsp->DFSFlags));
922
923         *target_nodes = kcalloc(*num_of_nodes, sizeof(struct dfs_info3_param),
924                                 GFP_KERNEL);
925         if (*target_nodes == NULL) {
926                 rc = -ENOMEM;
927                 goto parse_DFS_referrals_exit;
928         }
929
930         /* collect necessary data from referrals */
931         for (i = 0; i < *num_of_nodes; i++) {
932                 char *temp;
933                 int max_len;
934                 struct dfs_info3_param *node = (*target_nodes)+i;
935
936                 node->flags = le32_to_cpu(rsp->DFSFlags);
937                 if (is_unicode) {
938                         __le16 *tmp = kmalloc(strlen(searchName)*2 + 2,
939                                                 GFP_KERNEL);
940                         if (tmp == NULL) {
941                                 rc = -ENOMEM;
942                                 goto parse_DFS_referrals_exit;
943                         }
944                         cifsConvertToUTF16((__le16 *) tmp, searchName,
945                                            PATH_MAX, nls_codepage, remap);
946                         node->path_consumed = cifs_utf16_bytes(tmp,
947                                         le16_to_cpu(rsp->PathConsumed),
948                                         nls_codepage);
949                         kfree(tmp);
950                 } else
951                         node->path_consumed = le16_to_cpu(rsp->PathConsumed);
952
953                 node->server_type = le16_to_cpu(ref->ServerType);
954                 node->ref_flag = le16_to_cpu(ref->ReferralEntryFlags);
955
956                 /* copy DfsPath */
957                 temp = (char *)ref + le16_to_cpu(ref->DfsPathOffset);
958                 max_len = data_end - temp;
959                 node->path_name = cifs_strndup_from_utf16(temp, max_len,
960                                                 is_unicode, nls_codepage);
961                 if (!node->path_name) {
962                         rc = -ENOMEM;
963                         goto parse_DFS_referrals_exit;
964                 }
965
966                 /* copy link target UNC */
967                 temp = (char *)ref + le16_to_cpu(ref->NetworkAddressOffset);
968                 max_len = data_end - temp;
969                 node->node_name = cifs_strndup_from_utf16(temp, max_len,
970                                                 is_unicode, nls_codepage);
971                 if (!node->node_name) {
972                         rc = -ENOMEM;
973                         goto parse_DFS_referrals_exit;
974                 }
975
976                 node->ttl = le32_to_cpu(ref->TimeToLive);
977
978                 ref++;
979         }
980
981 parse_DFS_referrals_exit:
982         if (rc) {
983                 free_dfs_info_array(*target_nodes, *num_of_nodes);
984                 *target_nodes = NULL;
985                 *num_of_nodes = 0;
986         }
987         return rc;
988 }
989
990 struct cifs_aio_ctx *
991 cifs_aio_ctx_alloc(void)
992 {
993         struct cifs_aio_ctx *ctx;
994
995         /*
996          * Must use kzalloc to initialize ctx->bv to NULL and ctx->direct_io
997          * to false so that we know when we have to unreference pages within
998          * cifs_aio_ctx_release()
999          */
1000         ctx = kzalloc(sizeof(struct cifs_aio_ctx), GFP_KERNEL);
1001         if (!ctx)
1002                 return NULL;
1003
1004         INIT_LIST_HEAD(&ctx->list);
1005         mutex_init(&ctx->aio_mutex);
1006         init_completion(&ctx->done);
1007         kref_init(&ctx->refcount);
1008         return ctx;
1009 }
1010
1011 void
1012 cifs_aio_ctx_release(struct kref *refcount)
1013 {
1014         struct cifs_aio_ctx *ctx = container_of(refcount,
1015                                         struct cifs_aio_ctx, refcount);
1016
1017         cifsFileInfo_put(ctx->cfile);
1018
1019         /*
1020          * ctx->bv is only set if setup_aio_ctx_iter() was call successfuly
1021          * which means that iov_iter_extract_pages() was a success and thus
1022          * that we may have references or pins on pages that we need to
1023          * release.
1024          */
1025         if (ctx->bv) {
1026                 if (ctx->should_dirty || ctx->bv_need_unpin) {
1027                         unsigned int i;
1028
1029                         for (i = 0; i < ctx->nr_pinned_pages; i++) {
1030                                 struct page *page = ctx->bv[i].bv_page;
1031
1032                                 if (ctx->should_dirty)
1033                                         set_page_dirty(page);
1034                                 if (ctx->bv_need_unpin)
1035                                         unpin_user_page(page);
1036                         }
1037                 }
1038                 kvfree(ctx->bv);
1039         }
1040
1041         kfree(ctx);
1042 }
1043
1044 /**
1045  * cifs_alloc_hash - allocate hash and hash context together
1046  * @name: The name of the crypto hash algo
1047  * @sdesc: SHASH descriptor where to put the pointer to the hash TFM
1048  *
1049  * The caller has to make sure @sdesc is initialized to either NULL or
1050  * a valid context. It can be freed via cifs_free_hash().
1051  */
1052 int
1053 cifs_alloc_hash(const char *name, struct shash_desc **sdesc)
1054 {
1055         int rc = 0;
1056         struct crypto_shash *alg = NULL;
1057
1058         if (*sdesc)
1059                 return 0;
1060
1061         alg = crypto_alloc_shash(name, 0, 0);
1062         if (IS_ERR(alg)) {
1063                 cifs_dbg(VFS, "Could not allocate shash TFM '%s'\n", name);
1064                 rc = PTR_ERR(alg);
1065                 *sdesc = NULL;
1066                 return rc;
1067         }
1068
1069         *sdesc = kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(alg), GFP_KERNEL);
1070         if (*sdesc == NULL) {
1071                 cifs_dbg(VFS, "no memory left to allocate shash TFM '%s'\n", name);
1072                 crypto_free_shash(alg);
1073                 return -ENOMEM;
1074         }
1075
1076         (*sdesc)->tfm = alg;
1077         return 0;
1078 }
1079
1080 /**
1081  * cifs_free_hash - free hash and hash context together
1082  * @sdesc: Where to find the pointer to the hash TFM
1083  *
1084  * Freeing a NULL descriptor is safe.
1085  */
1086 void
1087 cifs_free_hash(struct shash_desc **sdesc)
1088 {
1089         if (unlikely(!sdesc) || !*sdesc)
1090                 return;
1091
1092         if ((*sdesc)->tfm) {
1093                 crypto_free_shash((*sdesc)->tfm);
1094                 (*sdesc)->tfm = NULL;
1095         }
1096
1097         kfree_sensitive(*sdesc);
1098         *sdesc = NULL;
1099 }
1100
1101 void extract_unc_hostname(const char *unc, const char **h, size_t *len)
1102 {
1103         const char *end;
1104
1105         /* skip initial slashes */
1106         while (*unc && (*unc == '\\' || *unc == '/'))
1107                 unc++;
1108
1109         end = unc;
1110
1111         while (*end && !(*end == '\\' || *end == '/'))
1112                 end++;
1113
1114         *h = unc;
1115         *len = end - unc;
1116 }
1117
1118 /**
1119  * copy_path_name - copy src path to dst, possibly truncating
1120  * @dst: The destination buffer
1121  * @src: The source name
1122  *
1123  * returns number of bytes written (including trailing nul)
1124  */
1125 int copy_path_name(char *dst, const char *src)
1126 {
1127         int name_len;
1128
1129         /*
1130          * PATH_MAX includes nul, so if strlen(src) >= PATH_MAX it
1131          * will truncate and strlen(dst) will be PATH_MAX-1
1132          */
1133         name_len = strscpy(dst, src, PATH_MAX);
1134         if (WARN_ON_ONCE(name_len < 0))
1135                 name_len = PATH_MAX-1;
1136
1137         /* we count the trailing nul */
1138         name_len++;
1139         return name_len;
1140 }
1141
1142 struct super_cb_data {
1143         void *data;
1144         struct super_block *sb;
1145 };
1146
1147 static void tcon_super_cb(struct super_block *sb, void *arg)
1148 {
1149         struct super_cb_data *sd = arg;
1150         struct cifs_sb_info *cifs_sb;
1151         struct cifs_tcon *t1 = sd->data, *t2;
1152
1153         if (sd->sb)
1154                 return;
1155
1156         cifs_sb = CIFS_SB(sb);
1157         t2 = cifs_sb_master_tcon(cifs_sb);
1158
1159         spin_lock(&t2->tc_lock);
1160         if (t1->ses == t2->ses &&
1161             t1->ses->server == t2->ses->server &&
1162             t2->origin_fullpath &&
1163             dfs_src_pathname_equal(t2->origin_fullpath, t1->origin_fullpath))
1164                 sd->sb = sb;
1165         spin_unlock(&t2->tc_lock);
1166 }
1167
1168 static struct super_block *__cifs_get_super(void (*f)(struct super_block *, void *),
1169                                             void *data)
1170 {
1171         struct super_cb_data sd = {
1172                 .data = data,
1173                 .sb = NULL,
1174         };
1175         struct file_system_type **fs_type = (struct file_system_type *[]) {
1176                 &cifs_fs_type, &smb3_fs_type, NULL,
1177         };
1178
1179         for (; *fs_type; fs_type++) {
1180                 iterate_supers_type(*fs_type, f, &sd);
1181                 if (sd.sb) {
1182                         /*
1183                          * Grab an active reference in order to prevent automounts (DFS links)
1184                          * of expiring and then freeing up our cifs superblock pointer while
1185                          * we're doing failover.
1186                          */
1187                         cifs_sb_active(sd.sb);
1188                         return sd.sb;
1189                 }
1190         }
1191         pr_warn_once("%s: could not find dfs superblock\n", __func__);
1192         return ERR_PTR(-EINVAL);
1193 }
1194
1195 static void __cifs_put_super(struct super_block *sb)
1196 {
1197         if (!IS_ERR_OR_NULL(sb))
1198                 cifs_sb_deactive(sb);
1199 }
1200
1201 struct super_block *cifs_get_dfs_tcon_super(struct cifs_tcon *tcon)
1202 {
1203         spin_lock(&tcon->tc_lock);
1204         if (!tcon->origin_fullpath) {
1205                 spin_unlock(&tcon->tc_lock);
1206                 return ERR_PTR(-ENOENT);
1207         }
1208         spin_unlock(&tcon->tc_lock);
1209         return __cifs_get_super(tcon_super_cb, tcon);
1210 }
1211
1212 void cifs_put_tcp_super(struct super_block *sb)
1213 {
1214         __cifs_put_super(sb);
1215 }
1216
1217 #ifdef CONFIG_CIFS_DFS_UPCALL
1218 int match_target_ip(struct TCP_Server_Info *server,
1219                     const char *share, size_t share_len,
1220                     bool *result)
1221 {
1222         int rc;
1223         char *target;
1224         struct sockaddr_storage ss;
1225
1226         *result = false;
1227
1228         target = kzalloc(share_len + 3, GFP_KERNEL);
1229         if (!target)
1230                 return -ENOMEM;
1231
1232         scnprintf(target, share_len + 3, "\\\\%.*s", (int)share_len, share);
1233
1234         cifs_dbg(FYI, "%s: target name: %s\n", __func__, target + 2);
1235
1236         rc = dns_resolve_server_name_to_ip(target, (struct sockaddr *)&ss, NULL);
1237         kfree(target);
1238
1239         if (rc < 0)
1240                 return rc;
1241
1242         spin_lock(&server->srv_lock);
1243         *result = cifs_match_ipaddr((struct sockaddr *)&server->dstaddr, (struct sockaddr *)&ss);
1244         spin_unlock(&server->srv_lock);
1245         cifs_dbg(FYI, "%s: ip addresses match: %u\n", __func__, *result);
1246         return 0;
1247 }
1248
1249 int cifs_update_super_prepath(struct cifs_sb_info *cifs_sb, char *prefix)
1250 {
1251         int rc;
1252
1253         kfree(cifs_sb->prepath);
1254         cifs_sb->prepath = NULL;
1255
1256         if (prefix && *prefix) {
1257                 cifs_sb->prepath = cifs_sanitize_prepath(prefix, GFP_ATOMIC);
1258                 if (IS_ERR(cifs_sb->prepath)) {
1259                         rc = PTR_ERR(cifs_sb->prepath);
1260                         cifs_sb->prepath = NULL;
1261                         return rc;
1262                 }
1263                 if (cifs_sb->prepath)
1264                         convert_delimiter(cifs_sb->prepath, CIFS_DIR_SEP(cifs_sb));
1265         }
1266
1267         cifs_sb->mnt_cifs_flags |= CIFS_MOUNT_USE_PREFIX_PATH;
1268         return 0;
1269 }
1270
1271 /*
1272  * Handle weird Windows SMB server behaviour. It responds with
1273  * STATUS_OBJECT_NAME_INVALID code to SMB2 QUERY_INFO request for
1274  * "\<server>\<dfsname>\<linkpath>" DFS reference, where <dfsname> contains
1275  * non-ASCII unicode symbols.
1276  */
1277 int cifs_inval_name_dfs_link_error(const unsigned int xid,
1278                                    struct cifs_tcon *tcon,
1279                                    struct cifs_sb_info *cifs_sb,
1280                                    const char *full_path,
1281                                    bool *islink)
1282 {
1283         struct cifs_ses *ses = tcon->ses;
1284         size_t len;
1285         char *path;
1286         char *ref_path;
1287
1288         *islink = false;
1289
1290         /*
1291          * Fast path - skip check when @full_path doesn't have a prefix path to
1292          * look up or tcon is not DFS.
1293          */
1294         if (strlen(full_path) < 2 || !cifs_sb ||
1295             (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_DFS) ||
1296             !is_tcon_dfs(tcon))
1297                 return 0;
1298
1299         spin_lock(&tcon->tc_lock);
1300         if (!tcon->origin_fullpath) {
1301                 spin_unlock(&tcon->tc_lock);
1302                 return 0;
1303         }
1304         spin_unlock(&tcon->tc_lock);
1305
1306         /*
1307          * Slow path - tcon is DFS and @full_path has prefix path, so attempt
1308          * to get a referral to figure out whether it is an DFS link.
1309          */
1310         len = strnlen(tcon->tree_name, MAX_TREE_SIZE + 1) + strlen(full_path) + 1;
1311         path = kmalloc(len, GFP_KERNEL);
1312         if (!path)
1313                 return -ENOMEM;
1314
1315         scnprintf(path, len, "%s%s", tcon->tree_name, full_path);
1316         ref_path = dfs_cache_canonical_path(path + 1, cifs_sb->local_nls,
1317                                             cifs_remap(cifs_sb));
1318         kfree(path);
1319
1320         if (IS_ERR(ref_path)) {
1321                 if (PTR_ERR(ref_path) != -EINVAL)
1322                         return PTR_ERR(ref_path);
1323         } else {
1324                 struct dfs_info3_param *refs = NULL;
1325                 int num_refs = 0;
1326
1327                 /*
1328                  * XXX: we are not using dfs_cache_find() here because we might
1329                  * end up filling all the DFS cache and thus potentially
1330                  * removing cached DFS targets that the client would eventually
1331                  * need during failover.
1332                  */
1333                 ses = CIFS_DFS_ROOT_SES(ses);
1334                 if (ses->server->ops->get_dfs_refer &&
1335                     !ses->server->ops->get_dfs_refer(xid, ses, ref_path, &refs,
1336                                                      &num_refs, cifs_sb->local_nls,
1337                                                      cifs_remap(cifs_sb)))
1338                         *islink = refs[0].server_type == DFS_TYPE_LINK;
1339                 free_dfs_info_array(refs, num_refs);
1340                 kfree(ref_path);
1341         }
1342         return 0;
1343 }
1344 #endif
1345
1346 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
1347 {
1348         int timeout = 10;
1349         int rc;
1350
1351         spin_lock(&server->srv_lock);
1352         if (server->tcpStatus != CifsNeedReconnect) {
1353                 spin_unlock(&server->srv_lock);
1354                 return 0;
1355         }
1356         timeout *= server->nr_targets;
1357         spin_unlock(&server->srv_lock);
1358
1359         /*
1360          * Give demultiplex thread up to 10 seconds to each target available for
1361          * reconnect -- should be greater than cifs socket timeout which is 7
1362          * seconds.
1363          *
1364          * On "soft" mounts we wait once. Hard mounts keep retrying until
1365          * process is killed or server comes back on-line.
1366          */
1367         do {
1368                 rc = wait_event_interruptible_timeout(server->response_q,
1369                                                       (server->tcpStatus != CifsNeedReconnect),
1370                                                       timeout * HZ);
1371                 if (rc < 0) {
1372                         cifs_dbg(FYI, "%s: aborting reconnect due to received signal\n",
1373                                  __func__);
1374                         return -ERESTARTSYS;
1375                 }
1376
1377                 /* are we still trying to reconnect? */
1378                 spin_lock(&server->srv_lock);
1379                 if (server->tcpStatus != CifsNeedReconnect) {
1380                         spin_unlock(&server->srv_lock);
1381                         return 0;
1382                 }
1383                 spin_unlock(&server->srv_lock);
1384         } while (retry);
1385
1386         cifs_dbg(FYI, "%s: gave up waiting on reconnect\n", __func__);
1387         return -EHOSTDOWN;
1388 }