GNU Linux-libre 5.15.137-gnu
[releases.git] / fs / cifs / cifsglob.h
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  *              Jeremy Allison (jra@samba.org)
7  *
8  */
9 #ifndef _CIFS_GLOB_H
10 #define _CIFS_GLOB_H
11
12 #include <linux/in.h>
13 #include <linux/in6.h>
14 #include <linux/inet.h>
15 #include <linux/slab.h>
16 #include <linux/scatterlist.h>
17 #include <linux/mm.h>
18 #include <linux/mempool.h>
19 #include <linux/workqueue.h>
20 #include "cifs_fs_sb.h"
21 #include "cifsacl.h"
22 #include <crypto/internal/hash.h>
23 #include <linux/scatterlist.h>
24 #include <uapi/linux/cifs/cifs_mount.h>
25 #include "smb2pdu.h"
26 #include "smb2glob.h"
27
28 #define CIFS_MAGIC_NUMBER 0xFF534D42      /* the first four bytes of SMB PDUs */
29
30 #define SMB_PATH_MAX 260
31 #define CIFS_PORT 445
32 #define RFC1001_PORT 139
33
34 /*
35  * The sizes of various internal tables and strings
36  */
37 #define MAX_UID_INFO 16
38 #define MAX_SES_INFO 2
39 #define MAX_TCON_INFO 4
40
41 #define MAX_TREE_SIZE (2 + CIFS_NI_MAXHOST + 1 + CIFS_MAX_SHARE_LEN + 1)
42
43 #define CIFS_MIN_RCV_POOL 4
44
45 #define MAX_REOPEN_ATT  5 /* these many maximum attempts to reopen a file */
46 /*
47  * default attribute cache timeout (jiffies)
48  */
49 #define CIFS_DEF_ACTIMEO (1 * HZ)
50
51 /*
52  * max attribute cache timeout (jiffies) - 2^30
53  */
54 #define CIFS_MAX_ACTIMEO (1 << 30)
55
56 /*
57  * Max persistent and resilient handle timeout (milliseconds).
58  * Windows durable max was 960000 (16 minutes)
59  */
60 #define SMB3_MAX_HANDLE_TIMEOUT 960000
61
62 /*
63  * MAX_REQ is the maximum number of requests that WE will send
64  * on one socket concurrently.
65  */
66 #define CIFS_MAX_REQ 32767
67
68 #define RFC1001_NAME_LEN 15
69 #define RFC1001_NAME_LEN_WITH_NULL (RFC1001_NAME_LEN + 1)
70
71 /* maximum length of ip addr as a string (including ipv6 and sctp) */
72 #define SERVER_NAME_LENGTH 80
73 #define SERVER_NAME_LEN_WITH_NULL     (SERVER_NAME_LENGTH + 1)
74
75 /* echo interval in seconds */
76 #define SMB_ECHO_INTERVAL_MIN 1
77 #define SMB_ECHO_INTERVAL_MAX 600
78 #define SMB_ECHO_INTERVAL_DEFAULT 60
79
80 /* dns resolution intervals in seconds */
81 #define SMB_DNS_RESOLVE_INTERVAL_MIN     120
82 #define SMB_DNS_RESOLVE_INTERVAL_DEFAULT 600
83
84 /* maximum number of PDUs in one compound */
85 #define MAX_COMPOUND 5
86
87 /*
88  * Default number of credits to keep available for SMB3.
89  * This value is chosen somewhat arbitrarily. The Windows client
90  * defaults to 128 credits, the Windows server allows clients up to
91  * 512 credits (or 8K for later versions), and the NetApp server
92  * does not limit clients at all.  Choose a high enough default value
93  * such that the client shouldn't limit performance, but allow mount
94  * to override (until you approach 64K, where we limit credits to 65000
95  * to reduce possibility of seeing more server credit overflow bugs.
96  */
97 #define SMB2_MAX_CREDITS_AVAILABLE 32000
98
99 #include "cifspdu.h"
100
101 #ifndef XATTR_DOS_ATTRIB
102 #define XATTR_DOS_ATTRIB "user.DOSATTRIB"
103 #endif
104
105 /*
106  * CIFS vfs client Status information (based on what we know.)
107  */
108
109 /* associated with each tcp and smb session */
110 enum statusEnum {
111         CifsNew = 0,
112         CifsGood,
113         CifsExiting,
114         CifsNeedReconnect,
115         CifsNeedNegotiate
116 };
117
118 enum securityEnum {
119         Unspecified = 0,        /* not specified */
120         NTLMv2,                 /* Legacy NTLM auth with NTLMv2 hash */
121         RawNTLMSSP,             /* NTLMSSP without SPNEGO, NTLMv2 hash */
122         Kerberos,               /* Kerberos via SPNEGO */
123 };
124
125 struct session_key {
126         unsigned int len;
127         char *response;
128 };
129
130 /* crypto security descriptor definition */
131 struct sdesc {
132         struct shash_desc shash;
133         char ctx[];
134 };
135
136 /* crypto hashing related structure/fields, not specific to a sec mech */
137 struct cifs_secmech {
138         struct crypto_shash *hmacmd5; /* hmac-md5 hash function */
139         struct crypto_shash *md5; /* md5 hash function */
140         struct crypto_shash *hmacsha256; /* hmac-sha256 hash function */
141         struct crypto_shash *cmacaes; /* block-cipher based MAC function */
142         struct crypto_shash *sha512; /* sha512 hash function */
143         struct sdesc *sdeschmacmd5;  /* ctxt to generate ntlmv2 hash, CR1 */
144         struct sdesc *sdescmd5; /* ctxt to generate cifs/smb signature */
145         struct sdesc *sdeschmacsha256;  /* ctxt to generate smb2 signature */
146         struct sdesc *sdesccmacaes;  /* ctxt to generate smb3 signature */
147         struct sdesc *sdescsha512; /* ctxt to generate smb3.11 signing key */
148         struct crypto_aead *ccmaesencrypt; /* smb3 encryption aead */
149         struct crypto_aead *ccmaesdecrypt; /* smb3 decryption aead */
150 };
151
152 /* per smb session structure/fields */
153 struct ntlmssp_auth {
154         bool sesskey_per_smbsess; /* whether session key is per smb session */
155         __u32 client_flags; /* sent by client in type 1 ntlmsssp exchange */
156         __u32 server_flags; /* sent by server in type 2 ntlmssp exchange */
157         unsigned char ciphertext[CIFS_CPHTXT_SIZE]; /* sent to server */
158         char cryptkey[CIFS_CRYPTO_KEY_SIZE]; /* used by ntlmssp */
159 };
160
161 struct cifs_cred {
162         int uid;
163         int gid;
164         int mode;
165         int cecount;
166         struct cifs_sid osid;
167         struct cifs_sid gsid;
168         struct cifs_ntace *ntaces;
169         struct cifs_ace *aces;
170 };
171
172 /*
173  *****************************************************************
174  * Except the CIFS PDUs themselves all the
175  * globally interesting structs should go here
176  *****************************************************************
177  */
178
179 /*
180  * A smb_rqst represents a complete request to be issued to a server. It's
181  * formed by a kvec array, followed by an array of pages. Page data is assumed
182  * to start at the beginning of the first page.
183  */
184 struct smb_rqst {
185         struct kvec     *rq_iov;        /* array of kvecs */
186         unsigned int    rq_nvec;        /* number of kvecs in array */
187         struct page     **rq_pages;     /* pointer to array of page ptrs */
188         unsigned int    rq_offset;      /* the offset to the 1st page */
189         unsigned int    rq_npages;      /* number pages in array */
190         unsigned int    rq_pagesz;      /* page size to use */
191         unsigned int    rq_tailsz;      /* length of last page */
192 };
193
194 struct mid_q_entry;
195 struct TCP_Server_Info;
196 struct cifsFileInfo;
197 struct cifs_ses;
198 struct cifs_tcon;
199 struct dfs_info3_param;
200 struct cifs_fattr;
201 struct smb3_fs_context;
202 struct cifs_fid;
203 struct cifs_readdata;
204 struct cifs_writedata;
205 struct cifs_io_parms;
206 struct cifs_search_info;
207 struct cifsInodeInfo;
208 struct cifs_open_parms;
209 struct cifs_credits;
210
211 struct smb_version_operations {
212         int (*send_cancel)(struct TCP_Server_Info *, struct smb_rqst *,
213                            struct mid_q_entry *);
214         bool (*compare_fids)(struct cifsFileInfo *, struct cifsFileInfo *);
215         /* setup request: allocate mid, sign message */
216         struct mid_q_entry *(*setup_request)(struct cifs_ses *,
217                                              struct TCP_Server_Info *,
218                                              struct smb_rqst *);
219         /* setup async request: allocate mid, sign message */
220         struct mid_q_entry *(*setup_async_request)(struct TCP_Server_Info *,
221                                                 struct smb_rqst *);
222         /* check response: verify signature, map error */
223         int (*check_receive)(struct mid_q_entry *, struct TCP_Server_Info *,
224                              bool);
225         void (*add_credits)(struct TCP_Server_Info *server,
226                             const struct cifs_credits *credits,
227                             const int optype);
228         void (*set_credits)(struct TCP_Server_Info *, const int);
229         int * (*get_credits_field)(struct TCP_Server_Info *, const int);
230         unsigned int (*get_credits)(struct mid_q_entry *);
231         __u64 (*get_next_mid)(struct TCP_Server_Info *);
232         void (*revert_current_mid)(struct TCP_Server_Info *server,
233                                    const unsigned int val);
234         /* data offset from read response message */
235         unsigned int (*read_data_offset)(char *);
236         /*
237          * Data length from read response message
238          * When in_remaining is true, the returned data length is in
239          * message field DataRemaining for out-of-band data read (e.g through
240          * Memory Registration RDMA write in SMBD).
241          * Otherwise, the returned data length is in message field DataLength.
242          */
243         unsigned int (*read_data_length)(char *, bool in_remaining);
244         /* map smb to linux error */
245         int (*map_error)(char *, bool);
246         /* find mid corresponding to the response message */
247         struct mid_q_entry * (*find_mid)(struct TCP_Server_Info *, char *);
248         void (*dump_detail)(void *buf, struct TCP_Server_Info *ptcp_info);
249         void (*clear_stats)(struct cifs_tcon *);
250         void (*print_stats)(struct seq_file *m, struct cifs_tcon *);
251         void (*dump_share_caps)(struct seq_file *, struct cifs_tcon *);
252         /* verify the message */
253         int (*check_message)(char *, unsigned int, struct TCP_Server_Info *);
254         bool (*is_oplock_break)(char *, struct TCP_Server_Info *);
255         int (*handle_cancelled_mid)(struct mid_q_entry *, struct TCP_Server_Info *);
256         void (*downgrade_oplock)(struct TCP_Server_Info *server,
257                                  struct cifsInodeInfo *cinode, __u32 oplock,
258                                  unsigned int epoch, bool *purge_cache);
259         /* process transaction2 response */
260         bool (*check_trans2)(struct mid_q_entry *, struct TCP_Server_Info *,
261                              char *, int);
262         /* check if we need to negotiate */
263         bool (*need_neg)(struct TCP_Server_Info *);
264         /* negotiate to the server */
265         int (*negotiate)(const unsigned int, struct cifs_ses *);
266         /* set negotiated write size */
267         unsigned int (*negotiate_wsize)(struct cifs_tcon *tcon, struct smb3_fs_context *ctx);
268         /* set negotiated read size */
269         unsigned int (*negotiate_rsize)(struct cifs_tcon *tcon, struct smb3_fs_context *ctx);
270         /* setup smb sessionn */
271         int (*sess_setup)(const unsigned int, struct cifs_ses *,
272                           const struct nls_table *);
273         /* close smb session */
274         int (*logoff)(const unsigned int, struct cifs_ses *);
275         /* connect to a server share */
276         int (*tree_connect)(const unsigned int, struct cifs_ses *, const char *,
277                             struct cifs_tcon *, const struct nls_table *);
278         /* close tree connecion */
279         int (*tree_disconnect)(const unsigned int, struct cifs_tcon *);
280         /* get DFS referrals */
281         int (*get_dfs_refer)(const unsigned int, struct cifs_ses *,
282                              const char *, struct dfs_info3_param **,
283                              unsigned int *, const struct nls_table *, int);
284         /* informational QFS call */
285         void (*qfs_tcon)(const unsigned int, struct cifs_tcon *,
286                          struct cifs_sb_info *);
287         /* check if a path is accessible or not */
288         int (*is_path_accessible)(const unsigned int, struct cifs_tcon *,
289                                   struct cifs_sb_info *, const char *);
290         /* query path data from the server */
291         int (*query_path_info)(const unsigned int, struct cifs_tcon *,
292                                struct cifs_sb_info *, const char *,
293                                FILE_ALL_INFO *, bool *, bool *);
294         /* query file data from the server */
295         int (*query_file_info)(const unsigned int, struct cifs_tcon *,
296                                struct cifs_fid *, FILE_ALL_INFO *);
297         /* query reparse tag from srv to determine which type of special file */
298         int (*query_reparse_tag)(const unsigned int xid, struct cifs_tcon *tcon,
299                                 struct cifs_sb_info *cifs_sb, const char *path,
300                                 __u32 *reparse_tag);
301         /* get server index number */
302         int (*get_srv_inum)(const unsigned int, struct cifs_tcon *,
303                             struct cifs_sb_info *, const char *,
304                             u64 *uniqueid, FILE_ALL_INFO *);
305         /* set size by path */
306         int (*set_path_size)(const unsigned int, struct cifs_tcon *,
307                              const char *, __u64, struct cifs_sb_info *, bool);
308         /* set size by file handle */
309         int (*set_file_size)(const unsigned int, struct cifs_tcon *,
310                              struct cifsFileInfo *, __u64, bool);
311         /* set attributes */
312         int (*set_file_info)(struct inode *, const char *, FILE_BASIC_INFO *,
313                              const unsigned int);
314         int (*set_compression)(const unsigned int, struct cifs_tcon *,
315                                struct cifsFileInfo *);
316         /* check if we can send an echo or nor */
317         bool (*can_echo)(struct TCP_Server_Info *);
318         /* send echo request */
319         int (*echo)(struct TCP_Server_Info *);
320         /* create directory */
321         int (*posix_mkdir)(const unsigned int xid, struct inode *inode,
322                         umode_t mode, struct cifs_tcon *tcon,
323                         const char *full_path,
324                         struct cifs_sb_info *cifs_sb);
325         int (*mkdir)(const unsigned int xid, struct inode *inode, umode_t mode,
326                      struct cifs_tcon *tcon, const char *name,
327                      struct cifs_sb_info *sb);
328         /* set info on created directory */
329         void (*mkdir_setinfo)(struct inode *, const char *,
330                               struct cifs_sb_info *, struct cifs_tcon *,
331                               const unsigned int);
332         /* remove directory */
333         int (*rmdir)(const unsigned int, struct cifs_tcon *, const char *,
334                      struct cifs_sb_info *);
335         /* unlink file */
336         int (*unlink)(const unsigned int, struct cifs_tcon *, const char *,
337                       struct cifs_sb_info *);
338         /* open, rename and delete file */
339         int (*rename_pending_delete)(const char *, struct dentry *,
340                                      const unsigned int);
341         /* send rename request */
342         int (*rename)(const unsigned int, struct cifs_tcon *, const char *,
343                       const char *, struct cifs_sb_info *);
344         /* send create hardlink request */
345         int (*create_hardlink)(const unsigned int, struct cifs_tcon *,
346                                const char *, const char *,
347                                struct cifs_sb_info *);
348         /* query symlink target */
349         int (*query_symlink)(const unsigned int, struct cifs_tcon *,
350                              struct cifs_sb_info *, const char *,
351                              char **, bool);
352         /* open a file for non-posix mounts */
353         int (*open)(const unsigned int, struct cifs_open_parms *,
354                     __u32 *, FILE_ALL_INFO *);
355         /* set fid protocol-specific info */
356         void (*set_fid)(struct cifsFileInfo *, struct cifs_fid *, __u32);
357         /* close a file */
358         void (*close)(const unsigned int, struct cifs_tcon *,
359                       struct cifs_fid *);
360         /* close a file, returning file attributes and timestamps */
361         void (*close_getattr)(const unsigned int xid, struct cifs_tcon *tcon,
362                       struct cifsFileInfo *pfile_info);
363         /* send a flush request to the server */
364         int (*flush)(const unsigned int, struct cifs_tcon *, struct cifs_fid *);
365         /* async read from the server */
366         int (*async_readv)(struct cifs_readdata *);
367         /* async write to the server */
368         int (*async_writev)(struct cifs_writedata *,
369                             void (*release)(struct kref *));
370         /* sync read from the server */
371         int (*sync_read)(const unsigned int, struct cifs_fid *,
372                          struct cifs_io_parms *, unsigned int *, char **,
373                          int *);
374         /* sync write to the server */
375         int (*sync_write)(const unsigned int, struct cifs_fid *,
376                           struct cifs_io_parms *, unsigned int *, struct kvec *,
377                           unsigned long);
378         /* open dir, start readdir */
379         int (*query_dir_first)(const unsigned int, struct cifs_tcon *,
380                                const char *, struct cifs_sb_info *,
381                                struct cifs_fid *, __u16,
382                                struct cifs_search_info *);
383         /* continue readdir */
384         int (*query_dir_next)(const unsigned int, struct cifs_tcon *,
385                               struct cifs_fid *,
386                               __u16, struct cifs_search_info *srch_inf);
387         /* close dir */
388         int (*close_dir)(const unsigned int, struct cifs_tcon *,
389                          struct cifs_fid *);
390         /* calculate a size of SMB message */
391         unsigned int (*calc_smb_size)(void *buf, struct TCP_Server_Info *ptcpi);
392         /* check for STATUS_PENDING and process the response if yes */
393         bool (*is_status_pending)(char *buf, struct TCP_Server_Info *server);
394         /* check for STATUS_NETWORK_SESSION_EXPIRED */
395         bool (*is_session_expired)(char *);
396         /* send oplock break response */
397         int (*oplock_response)(struct cifs_tcon *tcon, __u64 persistent_fid, __u64 volatile_fid,
398                         __u16 net_fid, struct cifsInodeInfo *cifs_inode);
399         /* query remote filesystem */
400         int (*queryfs)(const unsigned int, struct cifs_tcon *,
401                        struct cifs_sb_info *, struct kstatfs *);
402         /* send mandatory brlock to the server */
403         int (*mand_lock)(const unsigned int, struct cifsFileInfo *, __u64,
404                          __u64, __u32, int, int, bool);
405         /* unlock range of mandatory locks */
406         int (*mand_unlock_range)(struct cifsFileInfo *, struct file_lock *,
407                                  const unsigned int);
408         /* push brlocks from the cache to the server */
409         int (*push_mand_locks)(struct cifsFileInfo *);
410         /* get lease key of the inode */
411         void (*get_lease_key)(struct inode *, struct cifs_fid *);
412         /* set lease key of the inode */
413         void (*set_lease_key)(struct inode *, struct cifs_fid *);
414         /* generate new lease key */
415         void (*new_lease_key)(struct cifs_fid *);
416         int (*generate_signingkey)(struct cifs_ses *);
417         int (*calc_signature)(struct smb_rqst *, struct TCP_Server_Info *,
418                                 bool allocate_crypto);
419         int (*set_integrity)(const unsigned int, struct cifs_tcon *tcon,
420                              struct cifsFileInfo *src_file);
421         int (*enum_snapshots)(const unsigned int xid, struct cifs_tcon *tcon,
422                              struct cifsFileInfo *src_file, void __user *);
423         int (*notify)(const unsigned int xid, struct file *pfile,
424                              void __user *pbuf);
425         int (*query_mf_symlink)(unsigned int, struct cifs_tcon *,
426                                 struct cifs_sb_info *, const unsigned char *,
427                                 char *, unsigned int *);
428         int (*create_mf_symlink)(unsigned int, struct cifs_tcon *,
429                                  struct cifs_sb_info *, const unsigned char *,
430                                  char *, unsigned int *);
431         /* if we can do cache read operations */
432         bool (*is_read_op)(__u32);
433         /* set oplock level for the inode */
434         void (*set_oplock_level)(struct cifsInodeInfo *, __u32, unsigned int,
435                                  bool *);
436         /* create lease context buffer for CREATE request */
437         char * (*create_lease_buf)(u8 *lease_key, u8 oplock);
438         /* parse lease context buffer and return oplock/epoch info */
439         __u8 (*parse_lease_buf)(void *buf, unsigned int *epoch, char *lkey);
440         ssize_t (*copychunk_range)(const unsigned int,
441                         struct cifsFileInfo *src_file,
442                         struct cifsFileInfo *target_file,
443                         u64 src_off, u64 len, u64 dest_off);
444         int (*duplicate_extents)(const unsigned int, struct cifsFileInfo *src,
445                         struct cifsFileInfo *target_file, u64 src_off, u64 len,
446                         u64 dest_off);
447         int (*validate_negotiate)(const unsigned int, struct cifs_tcon *);
448         ssize_t (*query_all_EAs)(const unsigned int, struct cifs_tcon *,
449                         const unsigned char *, const unsigned char *, char *,
450                         size_t, struct cifs_sb_info *);
451         int (*set_EA)(const unsigned int, struct cifs_tcon *, const char *,
452                         const char *, const void *, const __u16,
453                         const struct nls_table *, struct cifs_sb_info *);
454         struct cifs_ntsd * (*get_acl)(struct cifs_sb_info *, struct inode *,
455                         const char *, u32 *, u32);
456         struct cifs_ntsd * (*get_acl_by_fid)(struct cifs_sb_info *,
457                         const struct cifs_fid *, u32 *, u32);
458         int (*set_acl)(struct cifs_ntsd *, __u32, struct inode *, const char *,
459                         int);
460         /* writepages retry size */
461         unsigned int (*wp_retry_size)(struct inode *);
462         /* get mtu credits */
463         int (*wait_mtu_credits)(struct TCP_Server_Info *, unsigned int,
464                                 unsigned int *, struct cifs_credits *);
465         /* adjust previously taken mtu credits to request size */
466         int (*adjust_credits)(struct TCP_Server_Info *server,
467                               struct cifs_credits *credits,
468                               const unsigned int payload_size);
469         /* check if we need to issue closedir */
470         bool (*dir_needs_close)(struct cifsFileInfo *);
471         long (*fallocate)(struct file *, struct cifs_tcon *, int, loff_t,
472                           loff_t);
473         /* init transform request - used for encryption for now */
474         int (*init_transform_rq)(struct TCP_Server_Info *, int num_rqst,
475                                  struct smb_rqst *, struct smb_rqst *);
476         int (*is_transform_hdr)(void *buf);
477         int (*receive_transform)(struct TCP_Server_Info *,
478                                  struct mid_q_entry **, char **, int *);
479         enum securityEnum (*select_sectype)(struct TCP_Server_Info *,
480                             enum securityEnum);
481         int (*next_header)(char *);
482         /* ioctl passthrough for query_info */
483         int (*ioctl_query_info)(const unsigned int xid,
484                                 struct cifs_tcon *tcon,
485                                 struct cifs_sb_info *cifs_sb,
486                                 __le16 *path, int is_dir,
487                                 unsigned long p);
488         /* make unix special files (block, char, fifo, socket) */
489         int (*make_node)(unsigned int xid,
490                          struct inode *inode,
491                          struct dentry *dentry,
492                          struct cifs_tcon *tcon,
493                          const char *full_path,
494                          umode_t mode,
495                          dev_t device_number);
496         /* version specific fiemap implementation */
497         int (*fiemap)(struct cifs_tcon *tcon, struct cifsFileInfo *,
498                       struct fiemap_extent_info *, u64, u64);
499         /* version specific llseek implementation */
500         loff_t (*llseek)(struct file *, struct cifs_tcon *, loff_t, int);
501         /* Check for STATUS_IO_TIMEOUT */
502         bool (*is_status_io_timeout)(char *buf);
503         /* Check for STATUS_NETWORK_NAME_DELETED */
504         void (*is_network_name_deleted)(char *buf, struct TCP_Server_Info *srv);
505 };
506
507 struct smb_version_values {
508         char            *version_string;
509         __u16           protocol_id;
510         __u32           req_capabilities;
511         __u32           large_lock_type;
512         __u32           exclusive_lock_type;
513         __u32           shared_lock_type;
514         __u32           unlock_lock_type;
515         size_t          header_preamble_size;
516         size_t          header_size;
517         size_t          max_header_size;
518         size_t          read_rsp_size;
519         __le16          lock_cmd;
520         unsigned int    cap_unix;
521         unsigned int    cap_nt_find;
522         unsigned int    cap_large_files;
523         __u16           signing_enabled;
524         __u16           signing_required;
525         size_t          create_lease_size;
526 };
527
528 #define HEADER_SIZE(server) (server->vals->header_size)
529 #define MAX_HEADER_SIZE(server) (server->vals->max_header_size)
530
531 /**
532  * CIFS superblock mount flags (mnt_cifs_flags) to consider when
533  * trying to reuse existing superblock for a new mount
534  */
535 #define CIFS_MOUNT_MASK (CIFS_MOUNT_NO_PERM | CIFS_MOUNT_SET_UID | \
536                          CIFS_MOUNT_SERVER_INUM | CIFS_MOUNT_DIRECT_IO | \
537                          CIFS_MOUNT_NO_XATTR | CIFS_MOUNT_MAP_SPECIAL_CHR | \
538                          CIFS_MOUNT_MAP_SFM_CHR | \
539                          CIFS_MOUNT_UNX_EMUL | CIFS_MOUNT_NO_BRL | \
540                          CIFS_MOUNT_CIFS_ACL | CIFS_MOUNT_OVERR_UID | \
541                          CIFS_MOUNT_OVERR_GID | CIFS_MOUNT_DYNPERM | \
542                          CIFS_MOUNT_NOPOSIXBRL | CIFS_MOUNT_NOSSYNC | \
543                          CIFS_MOUNT_FSCACHE | CIFS_MOUNT_MF_SYMLINKS | \
544                          CIFS_MOUNT_MULTIUSER | CIFS_MOUNT_STRICT_IO | \
545                          CIFS_MOUNT_CIFS_BACKUPUID | CIFS_MOUNT_CIFS_BACKUPGID | \
546                          CIFS_MOUNT_UID_FROM_ACL | CIFS_MOUNT_NO_HANDLE_CACHE | \
547                          CIFS_MOUNT_NO_DFS | CIFS_MOUNT_MODE_FROM_SID | \
548                          CIFS_MOUNT_RO_CACHE | CIFS_MOUNT_RW_CACHE)
549
550 /**
551  * Generic VFS superblock mount flags (s_flags) to consider when
552  * trying to reuse existing superblock for a new mount
553  */
554 #define CIFS_MS_MASK (SB_RDONLY | SB_MANDLOCK | SB_NOEXEC | SB_NOSUID | \
555                       SB_NODEV | SB_SYNCHRONOUS)
556
557 struct cifs_mnt_data {
558         struct cifs_sb_info *cifs_sb;
559         struct smb3_fs_context *ctx;
560         int flags;
561 };
562
563 static inline unsigned int
564 get_rfc1002_length(void *buf)
565 {
566         return be32_to_cpu(*((__be32 *)buf)) & 0xffffff;
567 }
568
569 static inline void
570 inc_rfc1001_len(void *buf, int count)
571 {
572         be32_add_cpu((__be32 *)buf, count);
573 }
574
575 struct TCP_Server_Info {
576         struct list_head tcp_ses_list;
577         struct list_head smb_ses_list;
578         __u64 conn_id; /* connection identifier (useful for debugging) */
579         int srv_count; /* reference counter */
580         /* 15 character server name + 0x20 16th byte indicating type = srv */
581         char server_RFC1001_name[RFC1001_NAME_LEN_WITH_NULL];
582         struct smb_version_operations   *ops;
583         struct smb_version_values       *vals;
584         /* updates to tcpStatus protected by GlobalMid_Lock */
585         enum statusEnum tcpStatus; /* what we think the status is */
586         char *hostname; /* hostname portion of UNC string */
587         struct socket *ssocket;
588         struct sockaddr_storage dstaddr;
589         struct sockaddr_storage srcaddr; /* locally bind to this IP */
590 #ifdef CONFIG_NET_NS
591         struct net *net;
592 #endif
593         wait_queue_head_t response_q;
594         wait_queue_head_t request_q; /* if more than maxmpx to srvr must block*/
595         struct list_head pending_mid_q;
596         bool noblocksnd;                /* use blocking sendmsg */
597         bool noautotune;                /* do not autotune send buf sizes */
598         bool nosharesock;
599         bool tcp_nodelay;
600         unsigned int credits;  /* send no more requests at once */
601         unsigned int max_credits; /* can override large 32000 default at mnt */
602         unsigned int in_flight;  /* number of requests on the wire to server */
603         unsigned int max_in_flight; /* max number of requests that were on wire */
604         spinlock_t req_lock;  /* protect the two values above */
605         struct mutex srv_mutex;
606         struct task_struct *tsk;
607         char server_GUID[16];
608         __u16 sec_mode;
609         bool sign; /* is signing enabled on this connection? */
610         bool ignore_signature:1; /* skip validation of signatures in SMB2/3 rsp */
611         bool session_estab; /* mark when very first sess is established */
612         int echo_credits;  /* echo reserved slots */
613         int oplock_credits;  /* oplock break reserved slots */
614         bool echoes:1; /* enable echoes */
615         __u8 client_guid[SMB2_CLIENT_GUID_SIZE]; /* Client GUID */
616         u16 dialect; /* dialect index that server chose */
617         bool oplocks:1; /* enable oplocks */
618         unsigned int maxReq;    /* Clients should submit no more */
619         /* than maxReq distinct unanswered SMBs to the server when using  */
620         /* multiplexed reads or writes (for SMB1/CIFS only, not SMB2/SMB3) */
621         unsigned int maxBuf;    /* maxBuf specifies the maximum */
622         /* message size the server can send or receive for non-raw SMBs */
623         /* maxBuf is returned by SMB NegotiateProtocol so maxBuf is only 0 */
624         /* when socket is setup (and during reconnect) before NegProt sent */
625         unsigned int max_rw;    /* maxRw specifies the maximum */
626         /* message size the server can send or receive for */
627         /* SMB_COM_WRITE_RAW or SMB_COM_READ_RAW. */
628         unsigned int capabilities; /* selective disabling of caps by smb sess */
629         int timeAdj;  /* Adjust for difference in server time zone in sec */
630         __u64 CurrentMid;         /* multiplex id - rotating counter, protected by GlobalMid_Lock */
631         char cryptkey[CIFS_CRYPTO_KEY_SIZE]; /* used by ntlm, ntlmv2 etc */
632         /* 16th byte of RFC1001 workstation name is always null */
633         char workstation_RFC1001_name[RFC1001_NAME_LEN_WITH_NULL];
634         __u32 sequence_number; /* for signing, protected by srv_mutex */
635         __u32 reconnect_instance; /* incremented on each reconnect */
636         struct session_key session_key;
637         unsigned long lstrp; /* when we got last response from this server */
638         struct cifs_secmech secmech; /* crypto sec mech functs, descriptors */
639 #define CIFS_NEGFLAVOR_UNENCAP  1       /* wct == 17, but no ext_sec */
640 #define CIFS_NEGFLAVOR_EXTENDED 2       /* wct == 17, ext_sec bit set */
641         char    negflavor;      /* NEGOTIATE response flavor */
642         /* extended security flavors that server supports */
643         bool    sec_ntlmssp;            /* supports NTLMSSP */
644         bool    sec_kerberosu2u;        /* supports U2U Kerberos */
645         bool    sec_kerberos;           /* supports plain Kerberos */
646         bool    sec_mskerberos;         /* supports legacy MS Kerberos */
647         bool    large_buf;              /* is current buffer large? */
648         /* use SMBD connection instead of socket */
649         bool    rdma;
650         /* point to the SMBD connection if RDMA is used instead of socket */
651         struct smbd_connection *smbd_conn;
652         struct delayed_work     echo; /* echo ping workqueue job */
653         struct delayed_work     resolve; /* dns resolution workqueue job */
654         char    *smallbuf;      /* pointer to current "small" buffer */
655         char    *bigbuf;        /* pointer to current "big" buffer */
656         /* Total size of this PDU. Only valid from cifs_demultiplex_thread */
657         unsigned int pdu_size;
658         unsigned int total_read; /* total amount of data read in this pass */
659         atomic_t in_send; /* requests trying to send */
660         atomic_t num_waiters;   /* blocked waiting to get in sendrecv */
661 #ifdef CONFIG_CIFS_FSCACHE
662         struct fscache_cookie   *fscache; /* client index cache cookie */
663 #endif
664 #ifdef CONFIG_CIFS_STATS2
665         atomic_t num_cmds[NUMBER_OF_SMB2_COMMANDS]; /* total requests by cmd */
666         atomic_t smb2slowcmd[NUMBER_OF_SMB2_COMMANDS]; /* count resps > 1 sec */
667         __u64 time_per_cmd[NUMBER_OF_SMB2_COMMANDS]; /* total time per cmd */
668         __u32 slowest_cmd[NUMBER_OF_SMB2_COMMANDS];
669         __u32 fastest_cmd[NUMBER_OF_SMB2_COMMANDS];
670 #endif /* STATS2 */
671         unsigned int    max_read;
672         unsigned int    max_write;
673         unsigned int    min_offload;
674         __le16  compress_algorithm;
675         __u16   signing_algorithm;
676         __le16  cipher_type;
677          /* save initital negprot hash */
678         __u8    preauth_sha_hash[SMB2_PREAUTH_HASH_SIZE];
679         bool    signing_negotiated; /* true if valid signing context rcvd from server */
680         bool    posix_ext_supported;
681         struct delayed_work reconnect; /* reconnect workqueue job */
682         struct mutex reconnect_mutex; /* prevent simultaneous reconnects */
683         unsigned long echo_interval;
684
685         /*
686          * Number of targets available for reconnect. The more targets
687          * the more tasks have to wait to let the demultiplex thread
688          * reconnect.
689          */
690         int nr_targets;
691         bool noblockcnt; /* use non-blocking connect() */
692         bool is_channel; /* if a session channel */
693 #ifdef CONFIG_CIFS_SWN_UPCALL
694         bool use_swn_dstaddr;
695         struct sockaddr_storage swn_dstaddr;
696 #endif
697 #ifdef CONFIG_CIFS_DFS_UPCALL
698         bool is_dfs_conn; /* if a dfs connection */
699         struct mutex refpath_lock; /* protects leaf_fullpath */
700         /*
701          * Canonical DFS full paths that were used to chase referrals in mount and reconnect.
702          *
703          * origin_fullpath: first or original referral path
704          * leaf_fullpath: last referral path (might be changed due to nested links in reconnect)
705          *
706          * current_fullpath: pointer to either origin_fullpath or leaf_fullpath
707          * NOTE: cannot be accessed outside cifs_reconnect() and smb2_reconnect()
708          *
709          * format: \\HOST\SHARE\[OPTIONAL PATH]
710          */
711         char *origin_fullpath, *leaf_fullpath, *current_fullpath;
712 #endif
713 };
714
715 struct cifs_credits {
716         unsigned int value;
717         unsigned int instance;
718 };
719
720 static inline unsigned int
721 in_flight(struct TCP_Server_Info *server)
722 {
723         unsigned int num;
724         spin_lock(&server->req_lock);
725         num = server->in_flight;
726         spin_unlock(&server->req_lock);
727         return num;
728 }
729
730 static inline bool
731 has_credits(struct TCP_Server_Info *server, int *credits, int num_credits)
732 {
733         int num;
734         spin_lock(&server->req_lock);
735         num = *credits;
736         spin_unlock(&server->req_lock);
737         return num >= num_credits;
738 }
739
740 static inline void
741 add_credits(struct TCP_Server_Info *server, const struct cifs_credits *credits,
742             const int optype)
743 {
744         server->ops->add_credits(server, credits, optype);
745 }
746
747 static inline void
748 add_credits_and_wake_if(struct TCP_Server_Info *server,
749                         const struct cifs_credits *credits, const int optype)
750 {
751         if (credits->value) {
752                 server->ops->add_credits(server, credits, optype);
753                 wake_up(&server->request_q);
754         }
755 }
756
757 static inline void
758 set_credits(struct TCP_Server_Info *server, const int val)
759 {
760         server->ops->set_credits(server, val);
761 }
762
763 static inline int
764 adjust_credits(struct TCP_Server_Info *server, struct cifs_credits *credits,
765                const unsigned int payload_size)
766 {
767         return server->ops->adjust_credits ?
768                 server->ops->adjust_credits(server, credits, payload_size) : 0;
769 }
770
771 static inline __le64
772 get_next_mid64(struct TCP_Server_Info *server)
773 {
774         return cpu_to_le64(server->ops->get_next_mid(server));
775 }
776
777 static inline __le16
778 get_next_mid(struct TCP_Server_Info *server)
779 {
780         __u16 mid = server->ops->get_next_mid(server);
781         /*
782          * The value in the SMB header should be little endian for easy
783          * on-the-wire decoding.
784          */
785         return cpu_to_le16(mid);
786 }
787
788 static inline void
789 revert_current_mid(struct TCP_Server_Info *server, const unsigned int val)
790 {
791         if (server->ops->revert_current_mid)
792                 server->ops->revert_current_mid(server, val);
793 }
794
795 static inline void
796 revert_current_mid_from_hdr(struct TCP_Server_Info *server,
797                             const struct smb2_sync_hdr *shdr)
798 {
799         unsigned int num = le16_to_cpu(shdr->CreditCharge);
800
801         return revert_current_mid(server, num > 0 ? num : 1);
802 }
803
804 static inline __u16
805 get_mid(const struct smb_hdr *smb)
806 {
807         return le16_to_cpu(smb->Mid);
808 }
809
810 static inline bool
811 compare_mid(__u16 mid, const struct smb_hdr *smb)
812 {
813         return mid == le16_to_cpu(smb->Mid);
814 }
815
816 /*
817  * When the server supports very large reads and writes via POSIX extensions,
818  * we can allow up to 2^24-1, minus the size of a READ/WRITE_AND_X header, not
819  * including the RFC1001 length.
820  *
821  * Note that this might make for "interesting" allocation problems during
822  * writeback however as we have to allocate an array of pointers for the
823  * pages. A 16M write means ~32kb page array with PAGE_SIZE == 4096.
824  *
825  * For reads, there is a similar problem as we need to allocate an array
826  * of kvecs to handle the receive, though that should only need to be done
827  * once.
828  */
829 #define CIFS_MAX_WSIZE ((1<<24) - 1 - sizeof(WRITE_REQ) + 4)
830 #define CIFS_MAX_RSIZE ((1<<24) - sizeof(READ_RSP) + 4)
831
832 /*
833  * When the server doesn't allow large posix writes, only allow a rsize/wsize
834  * of 2^17-1 minus the size of the call header. That allows for a read or
835  * write up to the maximum size described by RFC1002.
836  */
837 #define CIFS_MAX_RFC1002_WSIZE ((1<<17) - 1 - sizeof(WRITE_REQ) + 4)
838 #define CIFS_MAX_RFC1002_RSIZE ((1<<17) - 1 - sizeof(READ_RSP) + 4)
839
840 /*
841  * The default wsize is 1M. find_get_pages seems to return a maximum of 256
842  * pages in a single call. With PAGE_SIZE == 4k, this means we can fill
843  * a single wsize request with a single call.
844  */
845 #define CIFS_DEFAULT_IOSIZE (1024 * 1024)
846 #define SMB3_DEFAULT_IOSIZE (4 * 1024 * 1024)
847
848 /*
849  * Windows only supports a max of 60kb reads and 65535 byte writes. Default to
850  * those values when posix extensions aren't in force. In actuality here, we
851  * use 65536 to allow for a write that is a multiple of 4k. Most servers seem
852  * to be ok with the extra byte even though Windows doesn't send writes that
853  * are that large.
854  *
855  * Citation:
856  *
857  * https://blogs.msdn.com/b/openspecification/archive/2009/04/10/smb-maximum-transmit-buffer-size-and-performance-tuning.aspx
858  */
859 #define CIFS_DEFAULT_NON_POSIX_RSIZE (60 * 1024)
860 #define CIFS_DEFAULT_NON_POSIX_WSIZE (65536)
861
862 /*
863  * Macros to allow the TCP_Server_Info->net field and related code to drop out
864  * when CONFIG_NET_NS isn't set.
865  */
866
867 #ifdef CONFIG_NET_NS
868
869 static inline struct net *cifs_net_ns(struct TCP_Server_Info *srv)
870 {
871         return srv->net;
872 }
873
874 static inline void cifs_set_net_ns(struct TCP_Server_Info *srv, struct net *net)
875 {
876         srv->net = net;
877 }
878
879 #else
880
881 static inline struct net *cifs_net_ns(struct TCP_Server_Info *srv)
882 {
883         return &init_net;
884 }
885
886 static inline void cifs_set_net_ns(struct TCP_Server_Info *srv, struct net *net)
887 {
888 }
889
890 #endif
891
892 struct cifs_server_iface {
893         size_t speed;
894         unsigned int rdma_capable : 1;
895         unsigned int rss_capable : 1;
896         struct sockaddr_storage sockaddr;
897 };
898
899 struct cifs_chan {
900         struct TCP_Server_Info *server;
901         __u8 signkey[SMB3_SIGN_KEY_SIZE];
902 };
903
904 /*
905  * Session structure.  One of these for each uid session with a particular host
906  */
907 struct cifs_ses {
908         struct list_head smb_ses_list;
909         struct list_head tcon_list;
910         struct cifs_tcon *tcon_ipc;
911         struct mutex session_mutex;
912         struct TCP_Server_Info *server; /* pointer to server info */
913         int ses_count;          /* reference counter */
914         enum statusEnum status;  /* updates protected by GlobalMid_Lock */
915         unsigned overrideSecFlg;  /* if non-zero override global sec flags */
916         char *serverOS;         /* name of operating system underlying server */
917         char *serverNOS;        /* name of network operating system of server */
918         char *serverDomain;     /* security realm of server */
919         __u64 Suid;             /* remote smb uid  */
920         kuid_t linux_uid;       /* overriding owner of files on the mount */
921         kuid_t cred_uid;        /* owner of credentials */
922         unsigned int capabilities;
923         char ip_addr[INET6_ADDRSTRLEN + 1]; /* Max ipv6 (or v4) addr string len */
924         char *user_name;        /* must not be null except during init of sess
925                                    and after mount option parsing we fill it */
926         char *domainName;
927         char *password;
928         struct session_key auth_key;
929         struct ntlmssp_auth *ntlmssp; /* ciphertext, flags, server challenge */
930         enum securityEnum sectype; /* what security flavor was specified? */
931         bool sign;              /* is signing required? */
932         bool need_reconnect:1; /* connection reset, uid now invalid */
933         bool domainAuto:1;
934         bool binding:1; /* are we binding the session? */
935         __u16 session_flags;
936         __u8 smb3signingkey[SMB3_SIGN_KEY_SIZE];
937         __u8 smb3encryptionkey[SMB3_ENC_DEC_KEY_SIZE];
938         __u8 smb3decryptionkey[SMB3_ENC_DEC_KEY_SIZE];
939         __u8 preauth_sha_hash[SMB2_PREAUTH_HASH_SIZE];
940
941         __u8 binding_preauth_sha_hash[SMB2_PREAUTH_HASH_SIZE];
942
943         /*
944          * Network interfaces available on the server this session is
945          * connected to.
946          *
947          * Other channels can be opened by connecting and binding this
948          * session to interfaces from this list.
949          *
950          * iface_lock should be taken when accessing any of these fields
951          */
952         spinlock_t iface_lock;
953         /* ========= begin: protected by iface_lock ======== */
954         struct cifs_server_iface *iface_list;
955         size_t iface_count;
956         unsigned long iface_last_update; /* jiffies */
957         /* ========= end: protected by iface_lock ======== */
958
959         spinlock_t chan_lock;
960         /* ========= begin: protected by chan_lock ======== */
961 #define CIFS_MAX_CHANNELS 16
962         struct cifs_chan chans[CIFS_MAX_CHANNELS];
963         struct cifs_chan *binding_chan;
964         size_t chan_count;
965         size_t chan_max;
966         atomic_t chan_seq; /* round robin state */
967         /* ========= end: protected by chan_lock ======== */
968 };
969
970 /*
971  * When binding a new channel, we need to access the channel which isn't fully
972  * established yet.
973  */
974
975 static inline
976 struct cifs_chan *cifs_ses_binding_channel(struct cifs_ses *ses)
977 {
978         if (ses->binding)
979                 return ses->binding_chan;
980         else
981                 return NULL;
982 }
983
984 /*
985  * Returns the server pointer of the session. When binding a new
986  * channel this returns the last channel which isn't fully established
987  * yet.
988  *
989  * This function should be use for negprot/sess.setup codepaths. For
990  * the other requests see cifs_pick_channel().
991  */
992 static inline
993 struct TCP_Server_Info *cifs_ses_server(struct cifs_ses *ses)
994 {
995         if (ses->binding)
996                 return ses->binding_chan->server;
997         else
998                 return ses->server;
999 }
1000
1001 static inline bool
1002 cap_unix(struct cifs_ses *ses)
1003 {
1004         return ses->server->vals->cap_unix & ses->capabilities;
1005 }
1006
1007 struct cached_fid {
1008         bool is_valid:1;        /* Do we have a useable root fid */
1009         bool file_all_info_is_valid:1;
1010         bool has_lease:1;
1011         unsigned long time; /* jiffies of when lease was taken */
1012         struct kref refcount;
1013         struct cifs_fid *fid;
1014         struct mutex fid_mutex;
1015         struct cifs_tcon *tcon;
1016         struct dentry *dentry;
1017         struct work_struct lease_break;
1018         struct smb2_file_all_info file_all_info;
1019 };
1020
1021 /*
1022  * there is one of these for each connection to a resource on a particular
1023  * session
1024  */
1025 struct cifs_tcon {
1026         struct list_head tcon_list;
1027         int tc_count;
1028         struct list_head rlist; /* reconnect list */
1029         atomic_t num_local_opens;  /* num of all opens including disconnected */
1030         atomic_t num_remote_opens; /* num of all network opens on server */
1031         struct list_head openFileList;
1032         spinlock_t open_file_lock; /* protects list above */
1033         struct cifs_ses *ses;   /* pointer to session associated with */
1034         char treeName[MAX_TREE_SIZE + 1]; /* UNC name of resource in ASCII */
1035         char *nativeFileSystem;
1036         char *password;         /* for share-level security */
1037         __u32 tid;              /* The 4 byte tree id */
1038         __u16 Flags;            /* optional support bits */
1039         enum statusEnum tidStatus;
1040         atomic_t num_smbs_sent;
1041         union {
1042                 struct {
1043                         atomic_t num_writes;
1044                         atomic_t num_reads;
1045                         atomic_t num_flushes;
1046                         atomic_t num_oplock_brks;
1047                         atomic_t num_opens;
1048                         atomic_t num_closes;
1049                         atomic_t num_deletes;
1050                         atomic_t num_mkdirs;
1051                         atomic_t num_posixopens;
1052                         atomic_t num_posixmkdirs;
1053                         atomic_t num_rmdirs;
1054                         atomic_t num_renames;
1055                         atomic_t num_t2renames;
1056                         atomic_t num_ffirst;
1057                         atomic_t num_fnext;
1058                         atomic_t num_fclose;
1059                         atomic_t num_hardlinks;
1060                         atomic_t num_symlinks;
1061                         atomic_t num_locks;
1062                         atomic_t num_acl_get;
1063                         atomic_t num_acl_set;
1064                 } cifs_stats;
1065                 struct {
1066                         atomic_t smb2_com_sent[NUMBER_OF_SMB2_COMMANDS];
1067                         atomic_t smb2_com_failed[NUMBER_OF_SMB2_COMMANDS];
1068                 } smb2_stats;
1069         } stats;
1070         __u64    bytes_read;
1071         __u64    bytes_written;
1072         spinlock_t stat_lock;  /* protects the two fields above */
1073         FILE_SYSTEM_DEVICE_INFO fsDevInfo;
1074         FILE_SYSTEM_ATTRIBUTE_INFO fsAttrInfo; /* ok if fs name truncated */
1075         FILE_SYSTEM_UNIX_INFO fsUnixInfo;
1076         bool ipc:1;   /* set if connection to IPC$ share (always also pipe) */
1077         bool pipe:1;  /* set if connection to pipe share */
1078         bool print:1; /* set if connection to printer share */
1079         bool retry:1;
1080         bool nocase:1;
1081         bool nohandlecache:1; /* if strange server resource prob can turn off */
1082         bool nodelete:1;
1083         bool seal:1;      /* transport encryption for this mounted share */
1084         bool unix_ext:1;  /* if false disable Linux extensions to CIFS protocol
1085                                 for this mount even if server would support */
1086         bool posix_extensions; /* if true SMB3.11 posix extensions enabled */
1087         bool local_lease:1; /* check leases (only) on local system not remote */
1088         bool broken_posix_open; /* e.g. Samba server versions < 3.3.2, 3.2.9 */
1089         bool broken_sparse_sup; /* if server or share does not support sparse */
1090         bool need_reconnect:1; /* connection reset, tid now invalid */
1091         bool need_reopen_files:1; /* need to reopen tcon file handles */
1092         bool use_resilient:1; /* use resilient instead of durable handles */
1093         bool use_persistent:1; /* use persistent instead of durable handles */
1094         bool no_lease:1;    /* Do not request leases on files or directories */
1095         bool use_witness:1; /* use witness protocol */
1096         __le32 capabilities;
1097         __u32 share_flags;
1098         __u32 maximal_access;
1099         __u32 vol_serial_number;
1100         __le64 vol_create_time;
1101         __u64 snapshot_time; /* for timewarp tokens - timestamp of snapshot */
1102         __u32 handle_timeout; /* persistent and durable handle timeout in ms */
1103         __u32 ss_flags;         /* sector size flags */
1104         __u32 perf_sector_size; /* best sector size for perf */
1105         __u32 max_chunks;
1106         __u32 max_bytes_chunk;
1107         __u32 max_bytes_copy;
1108 #ifdef CONFIG_CIFS_FSCACHE
1109         u64 resource_id;                /* server resource id */
1110         struct fscache_cookie *fscache; /* cookie for share */
1111 #endif
1112         struct list_head pending_opens; /* list of incomplete opens */
1113         struct cached_fid crfid; /* Cached root fid */
1114         /* BB add field for back pointer to sb struct(s)? */
1115 #ifdef CONFIG_CIFS_DFS_UPCALL
1116         struct list_head ulist; /* cache update list */
1117 #endif
1118 };
1119
1120 /*
1121  * This is a refcounted and timestamped container for a tcon pointer. The
1122  * container holds a tcon reference. It is considered safe to free one of
1123  * these when the tl_count goes to 0. The tl_time is the time of the last
1124  * "get" on the container.
1125  */
1126 struct tcon_link {
1127         struct rb_node          tl_rbnode;
1128         kuid_t                  tl_uid;
1129         unsigned long           tl_flags;
1130 #define TCON_LINK_MASTER        0
1131 #define TCON_LINK_PENDING       1
1132 #define TCON_LINK_IN_TREE       2
1133         unsigned long           tl_time;
1134         atomic_t                tl_count;
1135         struct cifs_tcon        *tl_tcon;
1136 };
1137
1138 extern struct tcon_link *cifs_sb_tlink(struct cifs_sb_info *cifs_sb);
1139 extern void smb3_free_compound_rqst(int num_rqst, struct smb_rqst *rqst);
1140
1141 static inline struct cifs_tcon *
1142 tlink_tcon(struct tcon_link *tlink)
1143 {
1144         return tlink->tl_tcon;
1145 }
1146
1147 static inline struct tcon_link *
1148 cifs_sb_master_tlink(struct cifs_sb_info *cifs_sb)
1149 {
1150         return cifs_sb->master_tlink;
1151 }
1152
1153 extern void cifs_put_tlink(struct tcon_link *tlink);
1154
1155 static inline struct tcon_link *
1156 cifs_get_tlink(struct tcon_link *tlink)
1157 {
1158         if (tlink && !IS_ERR(tlink))
1159                 atomic_inc(&tlink->tl_count);
1160         return tlink;
1161 }
1162
1163 /* This function is always expected to succeed */
1164 extern struct cifs_tcon *cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb);
1165
1166 #define CIFS_OPLOCK_NO_CHANGE 0xfe
1167
1168 struct cifs_pending_open {
1169         struct list_head olist;
1170         struct tcon_link *tlink;
1171         __u8 lease_key[16];
1172         __u32 oplock;
1173 };
1174
1175 struct cifs_deferred_close {
1176         struct list_head dlist;
1177         struct tcon_link *tlink;
1178         __u16  netfid;
1179         __u64  persistent_fid;
1180         __u64  volatile_fid;
1181 };
1182
1183 /*
1184  * This info hangs off the cifsFileInfo structure, pointed to by llist.
1185  * This is used to track byte stream locks on the file
1186  */
1187 struct cifsLockInfo {
1188         struct list_head llist; /* pointer to next cifsLockInfo */
1189         struct list_head blist; /* pointer to locks blocked on this */
1190         wait_queue_head_t block_q;
1191         __u64 offset;
1192         __u64 length;
1193         __u32 pid;
1194         __u16 type;
1195         __u16 flags;
1196 };
1197
1198 /*
1199  * One of these for each open instance of a file
1200  */
1201 struct cifs_search_info {
1202         loff_t index_of_last_entry;
1203         __u16 entries_in_buffer;
1204         __u16 info_level;
1205         __u32 resume_key;
1206         char *ntwrk_buf_start;
1207         char *srch_entries_start;
1208         char *last_entry;
1209         const char *presume_name;
1210         unsigned int resume_name_len;
1211         bool endOfSearch:1;
1212         bool emptyDir:1;
1213         bool unicode:1;
1214         bool smallBuf:1; /* so we know which buf_release function to call */
1215 };
1216
1217 #define ACL_NO_MODE     ((umode_t)(-1))
1218 struct cifs_open_parms {
1219         struct cifs_tcon *tcon;
1220         struct cifs_sb_info *cifs_sb;
1221         int disposition;
1222         int desired_access;
1223         int create_options;
1224         const char *path;
1225         struct cifs_fid *fid;
1226         umode_t mode;
1227         bool reconnect:1;
1228 };
1229
1230 struct cifs_fid {
1231         __u16 netfid;
1232         __u64 persistent_fid;   /* persist file id for smb2 */
1233         __u64 volatile_fid;     /* volatile file id for smb2 */
1234         __u8 lease_key[SMB2_LEASE_KEY_SIZE];    /* lease key for smb2 */
1235         __u8 create_guid[16];
1236         __u32 access;
1237         struct cifs_pending_open *pending_open;
1238         unsigned int epoch;
1239 #ifdef CONFIG_CIFS_DEBUG2
1240         __u64 mid;
1241 #endif /* CIFS_DEBUG2 */
1242         bool purge_cache;
1243 };
1244
1245 struct cifs_fid_locks {
1246         struct list_head llist;
1247         struct cifsFileInfo *cfile;     /* fid that owns locks */
1248         struct list_head locks;         /* locks held by fid above */
1249 };
1250
1251 struct cifsFileInfo {
1252         /* following two lists are protected by tcon->open_file_lock */
1253         struct list_head tlist; /* pointer to next fid owned by tcon */
1254         struct list_head flist; /* next fid (file instance) for this inode */
1255         /* lock list below protected by cifsi->lock_sem */
1256         struct cifs_fid_locks *llist;   /* brlocks held by this fid */
1257         kuid_t uid;             /* allows finding which FileInfo structure */
1258         __u32 pid;              /* process id who opened file */
1259         struct cifs_fid fid;    /* file id from remote */
1260         struct list_head rlist; /* reconnect list */
1261         /* BB add lock scope info here if needed */ ;
1262         /* lock scope id (0 if none) */
1263         struct dentry *dentry;
1264         struct tcon_link *tlink;
1265         unsigned int f_flags;
1266         bool invalidHandle:1;   /* file closed via session abend */
1267         bool swapfile:1;
1268         bool oplock_break_cancelled:1;
1269         unsigned int oplock_epoch; /* epoch from the lease break */
1270         __u32 oplock_level; /* oplock/lease level from the lease break */
1271         int count;
1272         spinlock_t file_info_lock; /* protects four flag/count fields above */
1273         struct mutex fh_mutex; /* prevents reopen race after dead ses*/
1274         struct cifs_search_info srch_inf;
1275         struct work_struct oplock_break; /* work for oplock breaks */
1276         struct work_struct put; /* work for the final part of _put */
1277         struct delayed_work deferred;
1278         bool deferred_close_scheduled; /* Flag to indicate close is scheduled */
1279 };
1280
1281 struct cifs_io_parms {
1282         __u16 netfid;
1283         __u64 persistent_fid;   /* persist file id for smb2 */
1284         __u64 volatile_fid;     /* volatile file id for smb2 */
1285         __u32 pid;
1286         __u64 offset;
1287         unsigned int length;
1288         struct cifs_tcon *tcon;
1289         struct TCP_Server_Info *server;
1290 };
1291
1292 struct cifs_aio_ctx {
1293         struct kref             refcount;
1294         struct list_head        list;
1295         struct mutex            aio_mutex;
1296         struct completion       done;
1297         struct iov_iter         iter;
1298         struct kiocb            *iocb;
1299         struct cifsFileInfo     *cfile;
1300         struct bio_vec          *bv;
1301         loff_t                  pos;
1302         unsigned int            npages;
1303         ssize_t                 rc;
1304         unsigned int            len;
1305         unsigned int            total_len;
1306         bool                    should_dirty;
1307         /*
1308          * Indicates if this aio_ctx is for direct_io,
1309          * If yes, iter is a copy of the user passed iov_iter
1310          */
1311         bool                    direct_io;
1312 };
1313
1314 /* asynchronous read support */
1315 struct cifs_readdata {
1316         struct kref                     refcount;
1317         struct list_head                list;
1318         struct completion               done;
1319         struct cifsFileInfo             *cfile;
1320         struct address_space            *mapping;
1321         struct cifs_aio_ctx             *ctx;
1322         __u64                           offset;
1323         unsigned int                    bytes;
1324         unsigned int                    got_bytes;
1325         pid_t                           pid;
1326         int                             result;
1327         struct work_struct              work;
1328         int (*read_into_pages)(struct TCP_Server_Info *server,
1329                                 struct cifs_readdata *rdata,
1330                                 unsigned int len);
1331         int (*copy_into_pages)(struct TCP_Server_Info *server,
1332                                 struct cifs_readdata *rdata,
1333                                 struct iov_iter *iter);
1334         struct kvec                     iov[2];
1335         struct TCP_Server_Info          *server;
1336 #ifdef CONFIG_CIFS_SMB_DIRECT
1337         struct smbd_mr                  *mr;
1338 #endif
1339         unsigned int                    pagesz;
1340         unsigned int                    page_offset;
1341         unsigned int                    tailsz;
1342         struct cifs_credits             credits;
1343         unsigned int                    nr_pages;
1344         struct page                     **pages;
1345 };
1346
1347 /* asynchronous write support */
1348 struct cifs_writedata {
1349         struct kref                     refcount;
1350         struct list_head                list;
1351         struct completion               done;
1352         enum writeback_sync_modes       sync_mode;
1353         struct work_struct              work;
1354         struct cifsFileInfo             *cfile;
1355         struct cifs_aio_ctx             *ctx;
1356         __u64                           offset;
1357         pid_t                           pid;
1358         unsigned int                    bytes;
1359         int                             result;
1360         struct TCP_Server_Info          *server;
1361 #ifdef CONFIG_CIFS_SMB_DIRECT
1362         struct smbd_mr                  *mr;
1363 #endif
1364         unsigned int                    pagesz;
1365         unsigned int                    page_offset;
1366         unsigned int                    tailsz;
1367         struct cifs_credits             credits;
1368         unsigned int                    nr_pages;
1369         struct page                     **pages;
1370 };
1371
1372 /*
1373  * Take a reference on the file private data. Must be called with
1374  * cfile->file_info_lock held.
1375  */
1376 static inline void
1377 cifsFileInfo_get_locked(struct cifsFileInfo *cifs_file)
1378 {
1379         ++cifs_file->count;
1380 }
1381
1382 struct cifsFileInfo *cifsFileInfo_get(struct cifsFileInfo *cifs_file);
1383 void _cifsFileInfo_put(struct cifsFileInfo *cifs_file, bool wait_oplock_hdlr,
1384                        bool offload);
1385 void cifsFileInfo_put(struct cifsFileInfo *cifs_file);
1386
1387 #define CIFS_CACHE_READ_FLG     1
1388 #define CIFS_CACHE_HANDLE_FLG   2
1389 #define CIFS_CACHE_RH_FLG       (CIFS_CACHE_READ_FLG | CIFS_CACHE_HANDLE_FLG)
1390 #define CIFS_CACHE_WRITE_FLG    4
1391 #define CIFS_CACHE_RW_FLG       (CIFS_CACHE_READ_FLG | CIFS_CACHE_WRITE_FLG)
1392 #define CIFS_CACHE_RHW_FLG      (CIFS_CACHE_RW_FLG | CIFS_CACHE_HANDLE_FLG)
1393
1394 #define CIFS_CACHE_READ(cinode) ((cinode->oplock & CIFS_CACHE_READ_FLG) || (CIFS_SB(cinode->vfs_inode.i_sb)->mnt_cifs_flags & CIFS_MOUNT_RO_CACHE))
1395 #define CIFS_CACHE_HANDLE(cinode) (cinode->oplock & CIFS_CACHE_HANDLE_FLG)
1396 #define CIFS_CACHE_WRITE(cinode) ((cinode->oplock & CIFS_CACHE_WRITE_FLG) || (CIFS_SB(cinode->vfs_inode.i_sb)->mnt_cifs_flags & CIFS_MOUNT_RW_CACHE))
1397
1398 /*
1399  * One of these for each file inode
1400  */
1401
1402 struct cifsInodeInfo {
1403         bool can_cache_brlcks;
1404         struct list_head llist; /* locks helb by this inode */
1405         /*
1406          * NOTE: Some code paths call down_read(lock_sem) twice, so
1407          * we must always use cifs_down_write() instead of down_write()
1408          * for this semaphore to avoid deadlocks.
1409          */
1410         struct rw_semaphore lock_sem;   /* protect the fields above */
1411         /* BB add in lists for dirty pages i.e. write caching info for oplock */
1412         struct list_head openFileList;
1413         spinlock_t      open_file_lock; /* protects openFileList */
1414         __u32 cifsAttrs; /* e.g. DOS archive bit, sparse, compressed, system */
1415         unsigned int oplock;            /* oplock/lease level we have */
1416         unsigned int epoch;             /* used to track lease state changes */
1417 #define CIFS_INODE_PENDING_OPLOCK_BREAK   (0) /* oplock break in progress */
1418 #define CIFS_INODE_PENDING_WRITERS        (1) /* Writes in progress */
1419 #define CIFS_INODE_FLAG_UNUSED            (2) /* Unused flag */
1420 #define CIFS_INO_DELETE_PENDING           (3) /* delete pending on server */
1421 #define CIFS_INO_INVALID_MAPPING          (4) /* pagecache is invalid */
1422 #define CIFS_INO_LOCK                     (5) /* lock bit for synchronization */
1423 #define CIFS_INO_MODIFIED_ATTR            (6) /* Indicate change in mtime/ctime */
1424 #define CIFS_INO_CLOSE_ON_LOCK            (7) /* Not to defer the close when lock is set */
1425         unsigned long flags;
1426         spinlock_t writers_lock;
1427         unsigned int writers;           /* Number of writers on this inode */
1428         unsigned long time;             /* jiffies of last update of inode */
1429         u64  server_eof;                /* current file size on server -- protected by i_lock */
1430         u64  uniqueid;                  /* server inode number */
1431         u64  createtime;                /* creation time on server */
1432         __u8 lease_key[SMB2_LEASE_KEY_SIZE];    /* lease key for this inode */
1433 #ifdef CONFIG_CIFS_FSCACHE
1434         struct fscache_cookie *fscache;
1435 #endif
1436         struct inode vfs_inode;
1437         struct list_head deferred_closes; /* list of deferred closes */
1438         spinlock_t deferred_lock; /* protection on deferred list */
1439         bool lease_granted; /* Flag to indicate whether lease or oplock is granted. */
1440 };
1441
1442 static inline struct cifsInodeInfo *
1443 CIFS_I(struct inode *inode)
1444 {
1445         return container_of(inode, struct cifsInodeInfo, vfs_inode);
1446 }
1447
1448 static inline struct cifs_sb_info *
1449 CIFS_SB(struct super_block *sb)
1450 {
1451         return sb->s_fs_info;
1452 }
1453
1454 static inline struct cifs_sb_info *
1455 CIFS_FILE_SB(struct file *file)
1456 {
1457         return CIFS_SB(file_inode(file)->i_sb);
1458 }
1459
1460 static inline char CIFS_DIR_SEP(const struct cifs_sb_info *cifs_sb)
1461 {
1462         if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)
1463                 return '/';
1464         else
1465                 return '\\';
1466 }
1467
1468 static inline void
1469 convert_delimiter(char *path, char delim)
1470 {
1471         char old_delim, *pos;
1472
1473         if (delim == '/')
1474                 old_delim = '\\';
1475         else
1476                 old_delim = '/';
1477
1478         pos = path;
1479         while ((pos = strchr(pos, old_delim)))
1480                 *pos = delim;
1481 }
1482
1483 #define cifs_stats_inc atomic_inc
1484
1485 static inline void cifs_stats_bytes_written(struct cifs_tcon *tcon,
1486                                             unsigned int bytes)
1487 {
1488         if (bytes) {
1489                 spin_lock(&tcon->stat_lock);
1490                 tcon->bytes_written += bytes;
1491                 spin_unlock(&tcon->stat_lock);
1492         }
1493 }
1494
1495 static inline void cifs_stats_bytes_read(struct cifs_tcon *tcon,
1496                                          unsigned int bytes)
1497 {
1498         spin_lock(&tcon->stat_lock);
1499         tcon->bytes_read += bytes;
1500         spin_unlock(&tcon->stat_lock);
1501 }
1502
1503
1504 /*
1505  * This is the prototype for the mid receive function. This function is for
1506  * receiving the rest of the SMB frame, starting with the WordCount (which is
1507  * just after the MID in struct smb_hdr). Note:
1508  *
1509  * - This will be called by cifsd, with no locks held.
1510  * - The mid will still be on the pending_mid_q.
1511  * - mid->resp_buf will point to the current buffer.
1512  *
1513  * Returns zero on a successful receive, or an error. The receive state in
1514  * the TCP_Server_Info will also be updated.
1515  */
1516 typedef int (mid_receive_t)(struct TCP_Server_Info *server,
1517                             struct mid_q_entry *mid);
1518
1519 /*
1520  * This is the prototype for the mid callback function. This is called once the
1521  * mid has been received off of the socket. When creating one, take special
1522  * care to avoid deadlocks. Things to bear in mind:
1523  *
1524  * - it will be called by cifsd, with no locks held
1525  * - the mid will be removed from any lists
1526  */
1527 typedef void (mid_callback_t)(struct mid_q_entry *mid);
1528
1529 /*
1530  * This is the protopyte for mid handle function. This is called once the mid
1531  * has been recognized after decryption of the message.
1532  */
1533 typedef int (mid_handle_t)(struct TCP_Server_Info *server,
1534                             struct mid_q_entry *mid);
1535
1536 /* one of these for every pending CIFS request to the server */
1537 struct mid_q_entry {
1538         struct list_head qhead; /* mids waiting on reply from this server */
1539         struct kref refcount;
1540         struct TCP_Server_Info *server; /* server corresponding to this mid */
1541         __u64 mid;              /* multiplex id */
1542         __u16 credits;          /* number of credits consumed by this mid */
1543         __u16 credits_received; /* number of credits from the response */
1544         __u32 pid;              /* process id */
1545         __u32 sequence_number;  /* for CIFS signing */
1546         unsigned long when_alloc;  /* when mid was created */
1547 #ifdef CONFIG_CIFS_STATS2
1548         unsigned long when_sent; /* time when smb send finished */
1549         unsigned long when_received; /* when demux complete (taken off wire) */
1550 #endif
1551         mid_receive_t *receive; /* call receive callback */
1552         mid_callback_t *callback; /* call completion callback */
1553         mid_handle_t *handle; /* call handle mid callback */
1554         void *callback_data;      /* general purpose pointer for callback */
1555         struct task_struct *creator;
1556         void *resp_buf;         /* pointer to received SMB header */
1557         unsigned int resp_buf_size;
1558         int mid_state;  /* wish this were enum but can not pass to wait_event */
1559         unsigned int mid_flags;
1560         __le16 command;         /* smb command code */
1561         unsigned int optype;    /* operation type */
1562         bool large_buf:1;       /* if valid response, is pointer to large buf */
1563         bool multiRsp:1;        /* multiple trans2 responses for one request  */
1564         bool multiEnd:1;        /* both received */
1565         bool decrypted:1;       /* decrypted entry */
1566 };
1567
1568 struct close_cancelled_open {
1569         struct cifs_fid         fid;
1570         struct cifs_tcon        *tcon;
1571         struct work_struct      work;
1572         __u64 mid;
1573         __u16 cmd;
1574 };
1575
1576 /*      Make code in transport.c a little cleaner by moving
1577         update of optional stats into function below */
1578 static inline void cifs_in_send_inc(struct TCP_Server_Info *server)
1579 {
1580         atomic_inc(&server->in_send);
1581 }
1582
1583 static inline void cifs_in_send_dec(struct TCP_Server_Info *server)
1584 {
1585         atomic_dec(&server->in_send);
1586 }
1587
1588 static inline void cifs_num_waiters_inc(struct TCP_Server_Info *server)
1589 {
1590         atomic_inc(&server->num_waiters);
1591 }
1592
1593 static inline void cifs_num_waiters_dec(struct TCP_Server_Info *server)
1594 {
1595         atomic_dec(&server->num_waiters);
1596 }
1597
1598 #ifdef CONFIG_CIFS_STATS2
1599 static inline void cifs_save_when_sent(struct mid_q_entry *mid)
1600 {
1601         mid->when_sent = jiffies;
1602 }
1603 #else
1604 static inline void cifs_save_when_sent(struct mid_q_entry *mid)
1605 {
1606 }
1607 #endif
1608
1609 /* for pending dnotify requests */
1610 struct dir_notify_req {
1611         struct list_head lhead;
1612         __le16 Pid;
1613         __le16 PidHigh;
1614         __u16 Mid;
1615         __u16 Tid;
1616         __u16 Uid;
1617         __u16 netfid;
1618         __u32 filter; /* CompletionFilter (for multishot) */
1619         int multishot;
1620         struct file *pfile;
1621 };
1622
1623 struct dfs_info3_param {
1624         int flags; /* DFSREF_REFERRAL_SERVER, DFSREF_STORAGE_SERVER*/
1625         int path_consumed;
1626         int server_type;
1627         int ref_flag;
1628         char *path_name;
1629         char *node_name;
1630         int ttl;
1631 };
1632
1633 struct file_list {
1634         struct list_head list;
1635         struct cifsFileInfo *cfile;
1636 };
1637
1638 /*
1639  * common struct for holding inode info when searching for or updating an
1640  * inode with new info
1641  */
1642
1643 #define CIFS_FATTR_DFS_REFERRAL         0x1
1644 #define CIFS_FATTR_DELETE_PENDING       0x2
1645 #define CIFS_FATTR_NEED_REVAL           0x4
1646 #define CIFS_FATTR_INO_COLLISION        0x8
1647 #define CIFS_FATTR_UNKNOWN_NLINK        0x10
1648 #define CIFS_FATTR_FAKE_ROOT_INO        0x20
1649
1650 struct cifs_fattr {
1651         u32             cf_flags;
1652         u32             cf_cifsattrs;
1653         u64             cf_uniqueid;
1654         u64             cf_eof;
1655         u64             cf_bytes;
1656         u64             cf_createtime;
1657         kuid_t          cf_uid;
1658         kgid_t          cf_gid;
1659         umode_t         cf_mode;
1660         dev_t           cf_rdev;
1661         unsigned int    cf_nlink;
1662         unsigned int    cf_dtype;
1663         struct timespec64 cf_atime;
1664         struct timespec64 cf_mtime;
1665         struct timespec64 cf_ctime;
1666         u32             cf_cifstag;
1667 };
1668
1669 static inline void free_dfs_info_param(struct dfs_info3_param *param)
1670 {
1671         if (param) {
1672                 kfree(param->path_name);
1673                 kfree(param->node_name);
1674         }
1675 }
1676
1677 static inline void free_dfs_info_array(struct dfs_info3_param *param,
1678                                        int number_of_items)
1679 {
1680         int i;
1681         if ((number_of_items == 0) || (param == NULL))
1682                 return;
1683         for (i = 0; i < number_of_items; i++) {
1684                 kfree(param[i].path_name);
1685                 kfree(param[i].node_name);
1686         }
1687         kfree(param);
1688 }
1689
1690 static inline bool is_interrupt_error(int error)
1691 {
1692         switch (error) {
1693         case -EINTR:
1694         case -ERESTARTSYS:
1695         case -ERESTARTNOHAND:
1696         case -ERESTARTNOINTR:
1697                 return true;
1698         }
1699         return false;
1700 }
1701
1702 static inline bool is_retryable_error(int error)
1703 {
1704         if (is_interrupt_error(error) || error == -EAGAIN)
1705                 return true;
1706         return false;
1707 }
1708
1709
1710 /* cifs_get_writable_file() flags */
1711 #define FIND_WR_ANY         0
1712 #define FIND_WR_FSUID_ONLY  1
1713 #define FIND_WR_WITH_DELETE 2
1714
1715 #define   MID_FREE 0
1716 #define   MID_REQUEST_ALLOCATED 1
1717 #define   MID_REQUEST_SUBMITTED 2
1718 #define   MID_RESPONSE_RECEIVED 4
1719 #define   MID_RETRY_NEEDED      8 /* session closed while this request out */
1720 #define   MID_RESPONSE_MALFORMED 0x10
1721 #define   MID_SHUTDOWN           0x20
1722
1723 /* Flags */
1724 #define   MID_WAIT_CANCELLED     1 /* Cancelled while waiting for response */
1725 #define   MID_DELETED            2 /* Mid has been dequeued/deleted */
1726
1727 /* Types of response buffer returned from SendReceive2 */
1728 #define   CIFS_NO_BUFFER        0    /* Response buffer not returned */
1729 #define   CIFS_SMALL_BUFFER     1
1730 #define   CIFS_LARGE_BUFFER     2
1731 #define   CIFS_IOVEC            4    /* array of response buffers */
1732
1733 /* Type of Request to SendReceive2 */
1734 #define   CIFS_BLOCKING_OP      1    /* operation can block */
1735 #define   CIFS_NON_BLOCKING     2    /* do not block waiting for credits */
1736 #define   CIFS_TIMEOUT_MASK 0x003    /* only one of above set in req */
1737 #define   CIFS_LOG_ERROR    0x010    /* log NT STATUS if non-zero */
1738 #define   CIFS_LARGE_BUF_OP 0x020    /* large request buffer */
1739 #define   CIFS_NO_RSP_BUF   0x040    /* no response buffer required */
1740
1741 /* Type of request operation */
1742 #define   CIFS_ECHO_OP            0x080  /* echo request */
1743 #define   CIFS_OBREAK_OP          0x0100 /* oplock break request */
1744 #define   CIFS_NEG_OP             0x0200 /* negotiate request */
1745 #define   CIFS_CP_CREATE_CLOSE_OP 0x0400 /* compound create+close request */
1746 /* Lower bitmask values are reserved by others below. */
1747 #define   CIFS_SESS_OP            0x2000 /* session setup request */
1748 #define   CIFS_OP_MASK            0x2780 /* mask request type */
1749
1750 #define   CIFS_HAS_CREDITS        0x0400 /* already has credits */
1751 #define   CIFS_TRANSFORM_REQ      0x0800 /* transform request before sending */
1752 #define   CIFS_NO_SRV_RSP         0x1000 /* there is no server response */
1753
1754 /* Security Flags: indicate type of session setup needed */
1755 #define   CIFSSEC_MAY_SIGN      0x00001
1756 #define   CIFSSEC_MAY_NTLMV2    0x00004
1757 #define   CIFSSEC_MAY_KRB5      0x00008
1758 #define   CIFSSEC_MAY_SEAL      0x00040 /* not supported yet */
1759 #define   CIFSSEC_MAY_NTLMSSP   0x00080 /* raw ntlmssp with ntlmv2 */
1760
1761 #define   CIFSSEC_MUST_SIGN     0x01001
1762 /* note that only one of the following can be set so the
1763 result of setting MUST flags more than once will be to
1764 require use of the stronger protocol */
1765 #define   CIFSSEC_MUST_NTLMV2   0x04004
1766 #define   CIFSSEC_MUST_KRB5     0x08008
1767 #ifdef CONFIG_CIFS_UPCALL
1768 #define   CIFSSEC_MASK          0x8F08F /* flags supported if no weak allowed */
1769 #else
1770 #define   CIFSSEC_MASK          0x87087 /* flags supported if no weak allowed */
1771 #endif /* UPCALL */
1772 #define   CIFSSEC_MUST_SEAL     0x40040 /* not supported yet */
1773 #define   CIFSSEC_MUST_NTLMSSP  0x80080 /* raw ntlmssp with ntlmv2 */
1774
1775 #define   CIFSSEC_DEF (CIFSSEC_MAY_SIGN | CIFSSEC_MAY_NTLMV2 | CIFSSEC_MAY_NTLMSSP)
1776 #define   CIFSSEC_MAX (CIFSSEC_MUST_NTLMV2)
1777 #define   CIFSSEC_AUTH_MASK (CIFSSEC_MAY_NTLMV2 | CIFSSEC_MAY_KRB5 | CIFSSEC_MAY_NTLMSSP)
1778 /*
1779  *****************************************************************
1780  * All constants go here
1781  *****************************************************************
1782  */
1783
1784 #define UID_HASH (16)
1785
1786 /*
1787  * Note that ONE module should define _DECLARE_GLOBALS_HERE to cause the
1788  * following to be declared.
1789  */
1790
1791 /****************************************************************************
1792  *  Locking notes.  All updates to global variables and lists should be
1793  *                  protected by spinlocks or semaphores.
1794  *
1795  *  Spinlocks
1796  *  ---------
1797  *  GlobalMid_Lock protects:
1798  *      list operations on pending_mid_q and oplockQ
1799  *      updates to XID counters, multiplex id  and SMB sequence numbers
1800  *      list operations on global DnotifyReqList
1801  *      updates to ses->status and TCP_Server_Info->tcpStatus
1802  *      updates to server->CurrentMid
1803  *  tcp_ses_lock protects:
1804  *      list operations on tcp and SMB session lists
1805  *  tcon->open_file_lock protects the list of open files hanging off the tcon
1806  *  inode->open_file_lock protects the openFileList hanging off the inode
1807  *  cfile->file_info_lock protects counters and fields in cifs file struct
1808  *  f_owner.lock protects certain per file struct operations
1809  *  mapping->page_lock protects certain per page operations
1810  *
1811  *  Note that the cifs_tcon.open_file_lock should be taken before
1812  *  not after the cifsInodeInfo.open_file_lock
1813  *
1814  *  Semaphores
1815  *  ----------
1816  *  cifsInodeInfo->lock_sem protects:
1817  *      the list of locks held by the inode
1818  *
1819  ****************************************************************************/
1820
1821 #ifdef DECLARE_GLOBALS_HERE
1822 #define GLOBAL_EXTERN
1823 #else
1824 #define GLOBAL_EXTERN extern
1825 #endif
1826
1827 /*
1828  * the list of TCP_Server_Info structures, ie each of the sockets
1829  * connecting our client to a distinct server (ip address), is
1830  * chained together by cifs_tcp_ses_list. The list of all our SMB
1831  * sessions (and from that the tree connections) can be found
1832  * by iterating over cifs_tcp_ses_list
1833  */
1834 GLOBAL_EXTERN struct list_head          cifs_tcp_ses_list;
1835
1836 /*
1837  * This lock protects the cifs_tcp_ses_list, the list of smb sessions per
1838  * tcp session, and the list of tcon's per smb session. It also protects
1839  * the reference counters for the server, smb session, and tcon. It also
1840  * protects some fields in the TCP_Server_Info struct such as dstaddr. Finally,
1841  * changes to the tcon->tidStatus should be done while holding this lock.
1842  * generally the locks should be taken in order tcp_ses_lock before
1843  * tcon->open_file_lock and that before file->file_info_lock since the
1844  * structure order is cifs_socket-->cifs_ses-->cifs_tcon-->cifs_file
1845  */
1846 GLOBAL_EXTERN spinlock_t                cifs_tcp_ses_lock;
1847
1848 /*
1849  * Global transaction id (XID) information
1850  */
1851 GLOBAL_EXTERN unsigned int GlobalCurrentXid;    /* protected by GlobalMid_Sem */
1852 GLOBAL_EXTERN unsigned int GlobalTotalActiveXid; /* prot by GlobalMid_Sem */
1853 GLOBAL_EXTERN unsigned int GlobalMaxActiveXid;  /* prot by GlobalMid_Sem */
1854 GLOBAL_EXTERN spinlock_t GlobalMid_Lock;  /* protects above & list operations */
1855                                           /* on midQ entries */
1856 /*
1857  *  Global counters, updated atomically
1858  */
1859 GLOBAL_EXTERN atomic_t sesInfoAllocCount;
1860 GLOBAL_EXTERN atomic_t tconInfoAllocCount;
1861 GLOBAL_EXTERN atomic_t tcpSesNextId;
1862 GLOBAL_EXTERN atomic_t tcpSesAllocCount;
1863 GLOBAL_EXTERN atomic_t tcpSesReconnectCount;
1864 GLOBAL_EXTERN atomic_t tconInfoReconnectCount;
1865
1866 /* Various Debug counters */
1867 GLOBAL_EXTERN atomic_t bufAllocCount;    /* current number allocated  */
1868 #ifdef CONFIG_CIFS_STATS2
1869 GLOBAL_EXTERN atomic_t totBufAllocCount; /* total allocated over all time */
1870 GLOBAL_EXTERN atomic_t totSmBufAllocCount;
1871 extern unsigned int slow_rsp_threshold; /* number of secs before logging */
1872 #endif
1873 GLOBAL_EXTERN atomic_t smBufAllocCount;
1874 GLOBAL_EXTERN atomic_t midCount;
1875
1876 /* Misc globals */
1877 extern bool enable_oplocks; /* enable or disable oplocks */
1878 extern bool lookupCacheEnabled;
1879 extern unsigned int global_secflags;    /* if on, session setup sent
1880                                 with more secure ntlmssp2 challenge/resp */
1881 extern unsigned int sign_CIFS_PDUs;  /* enable smb packet signing */
1882 extern bool enable_gcm_256; /* allow optional negotiate of strongest signing (aes-gcm-256) */
1883 extern bool require_gcm_256; /* require use of strongest signing (aes-gcm-256) */
1884 extern bool enable_negotiate_signing; /* request use of faster (GMAC) signing if available */
1885 extern bool linuxExtEnabled;/*enable Linux/Unix CIFS extensions*/
1886 extern unsigned int CIFSMaxBufSize;  /* max size not including hdr */
1887 extern unsigned int cifs_min_rcv;    /* min size of big ntwrk buf pool */
1888 extern unsigned int cifs_min_small;  /* min size of small buf pool */
1889 extern unsigned int cifs_max_pending; /* MAX requests at once to server*/
1890 extern bool disable_legacy_dialects;  /* forbid vers=1.0 and vers=2.0 mounts */
1891
1892 void cifs_oplock_break(struct work_struct *work);
1893 void cifs_queue_oplock_break(struct cifsFileInfo *cfile);
1894 void smb2_deferred_work_close(struct work_struct *work);
1895
1896 extern const struct slow_work_ops cifs_oplock_break_ops;
1897 extern struct workqueue_struct *cifsiod_wq;
1898 extern struct workqueue_struct *decrypt_wq;
1899 extern struct workqueue_struct *fileinfo_put_wq;
1900 extern struct workqueue_struct *cifsoplockd_wq;
1901 extern struct workqueue_struct *deferredclose_wq;
1902 extern __u32 cifs_lock_secret;
1903
1904 extern mempool_t *cifs_mid_poolp;
1905
1906 /* Operations for different SMB versions */
1907 #define SMB1_VERSION_STRING     "1.0"
1908 #define SMB20_VERSION_STRING    "2.0"
1909 #ifdef CONFIG_CIFS_ALLOW_INSECURE_LEGACY
1910 extern struct smb_version_operations smb1_operations;
1911 extern struct smb_version_values smb1_values;
1912 extern struct smb_version_operations smb20_operations;
1913 extern struct smb_version_values smb20_values;
1914 #endif /* CIFS_ALLOW_INSECURE_LEGACY */
1915 #define SMB21_VERSION_STRING    "2.1"
1916 extern struct smb_version_operations smb21_operations;
1917 extern struct smb_version_values smb21_values;
1918 #define SMBDEFAULT_VERSION_STRING "default"
1919 extern struct smb_version_values smbdefault_values;
1920 #define SMB3ANY_VERSION_STRING "3"
1921 extern struct smb_version_values smb3any_values;
1922 #define SMB30_VERSION_STRING    "3.0"
1923 extern struct smb_version_operations smb30_operations;
1924 extern struct smb_version_values smb30_values;
1925 #define SMB302_VERSION_STRING   "3.02"
1926 #define ALT_SMB302_VERSION_STRING "3.0.2"
1927 /*extern struct smb_version_operations smb302_operations;*/ /* not needed yet */
1928 extern struct smb_version_values smb302_values;
1929 #define SMB311_VERSION_STRING   "3.1.1"
1930 #define ALT_SMB311_VERSION_STRING "3.11"
1931 extern struct smb_version_operations smb311_operations;
1932 extern struct smb_version_values smb311_values;
1933
1934 static inline char *get_security_type_str(enum securityEnum sectype)
1935 {
1936         switch (sectype) {
1937         case RawNTLMSSP:
1938                 return "RawNTLMSSP";
1939         case Kerberos:
1940                 return "Kerberos";
1941         case NTLMv2:
1942                 return "NTLMv2";
1943         default:
1944                 return "Unknown";
1945         }
1946 }
1947
1948 static inline bool is_smb1_server(struct TCP_Server_Info *server)
1949 {
1950         return strcmp(server->vals->version_string, SMB1_VERSION_STRING) == 0;
1951 }
1952
1953 static inline bool is_tcon_dfs(struct cifs_tcon *tcon)
1954 {
1955         /*
1956          * For SMB1, see MS-CIFS 2.4.55 SMB_COM_TREE_CONNECT_ANDX (0x75) and MS-CIFS 3.3.4.4 DFS
1957          * Subsystem Notifies That a Share Is a DFS Share.
1958          *
1959          * For SMB2+, see MS-SMB2 2.2.10 SMB2 TREE_CONNECT Response and MS-SMB2 3.3.4.14 Server
1960          * Application Updates a Share.
1961          */
1962         if (!tcon || !tcon->ses || !tcon->ses->server)
1963                 return false;
1964         return is_smb1_server(tcon->ses->server) ? tcon->Flags & SMB_SHARE_IS_IN_DFS :
1965                 tcon->share_flags & (SHI1005_FLAGS_DFS | SHI1005_FLAGS_DFS_ROOT);
1966 }
1967
1968 static inline bool cifs_is_referral_server(struct cifs_tcon *tcon,
1969                                            const struct dfs_info3_param *ref)
1970 {
1971         /*
1972          * Check if all targets are capable of handling DFS referrals as per
1973          * MS-DFSC 2.2.4 RESP_GET_DFS_REFERRAL.
1974          */
1975         return is_tcon_dfs(tcon) || (ref && (ref->flags & DFSREF_REFERRAL_SERVER));
1976 }
1977
1978 static inline unsigned int cifs_get_num_sgs(const struct smb_rqst *rqst,
1979                                             int num_rqst,
1980                                             const u8 *sig)
1981 {
1982         unsigned int len, skip;
1983         unsigned int nents = 0;
1984         unsigned long addr;
1985         int i, j;
1986
1987         /* Assumes the first rqst has a transform header as the first iov.
1988          * I.e.
1989          * rqst[0].rq_iov[0]  is transform header
1990          * rqst[0].rq_iov[1+] data to be encrypted/decrypted
1991          * rqst[1+].rq_iov[0+] data to be encrypted/decrypted
1992          */
1993         for (i = 0; i < num_rqst; i++) {
1994                 /*
1995                  * The first rqst has a transform header where the
1996                  * first 20 bytes are not part of the encrypted blob.
1997                  */
1998                 for (j = 0; j < rqst[i].rq_nvec; j++) {
1999                         struct kvec *iov = &rqst[i].rq_iov[j];
2000
2001                         skip = (i == 0) && (j == 0) ? 20 : 0;
2002                         addr = (unsigned long)iov->iov_base + skip;
2003                         if (unlikely(is_vmalloc_addr((void *)addr))) {
2004                                 len = iov->iov_len - skip;
2005                                 nents += DIV_ROUND_UP(offset_in_page(addr) + len,
2006                                                       PAGE_SIZE);
2007                         } else {
2008                                 nents++;
2009                         }
2010                 }
2011                 nents += rqst[i].rq_npages;
2012         }
2013         nents += DIV_ROUND_UP(offset_in_page(sig) + SMB2_SIGNATURE_SIZE, PAGE_SIZE);
2014         return nents;
2015 }
2016
2017 /* We can not use the normal sg_set_buf() as we will sometimes pass a
2018  * stack object as buf.
2019  */
2020 static inline struct scatterlist *cifs_sg_set_buf(struct scatterlist *sg,
2021                                                   const void *buf,
2022                                                   unsigned int buflen)
2023 {
2024         unsigned long addr = (unsigned long)buf;
2025         unsigned int off = offset_in_page(addr);
2026
2027         addr &= PAGE_MASK;
2028         if (unlikely(is_vmalloc_addr((void *)addr))) {
2029                 do {
2030                         unsigned int len = min_t(unsigned int, buflen, PAGE_SIZE - off);
2031
2032                         sg_set_page(sg++, vmalloc_to_page((void *)addr), len, off);
2033
2034                         off = 0;
2035                         addr += PAGE_SIZE;
2036                         buflen -= len;
2037                 } while (buflen);
2038         } else {
2039                 sg_set_page(sg++, virt_to_page(addr), buflen, off);
2040         }
2041         return sg;
2042 }
2043
2044 #endif  /* _CIFS_GLOB_H */