From 4478441145be4d8fd3d8b4562b84aade98c4787f Mon Sep 17 00:00:00 2001 From: John Baldwin Date: Wed, 13 Apr 2016 17:37:31 +0000 Subject: [PATCH 001/143] Expose doreti as a global symbol on amd64 and i386. doreti provides the common code path for returning from interrupt andlers on x86. Exposing doreti as a global symbol allows kernel modules to include low-level interrupt handlers instead of requiring all low-level handlers to be statically compiled into the kernel. Submitted by: Howard Su Reviewed by: kib --- sys/amd64/amd64/exception.S | 1 + sys/i386/i386/exception.s | 1 + 2 files changed, 2 insertions(+) diff --git a/sys/amd64/amd64/exception.S b/sys/amd64/amd64/exception.S index caabfd9f0cd4..fd8cdac989f2 100644 --- a/sys/amd64/amd64/exception.S +++ b/sys/amd64/amd64/exception.S @@ -659,6 +659,7 @@ MCOUNT_LABEL(eintr) .text SUPERALIGN_TEXT .type doreti,@function + .globl doreti doreti: FAKE_MCOUNT($bintr) /* init "from" bintr -> doreti */ /* diff --git a/sys/i386/i386/exception.s b/sys/i386/i386/exception.s index f91f51612269..c03cbce20eb5 100644 --- a/sys/i386/i386/exception.s +++ b/sys/i386/i386/exception.s @@ -343,6 +343,7 @@ MCOUNT_LABEL(eintr) .text SUPERALIGN_TEXT .type doreti,@function + .globl doreti doreti: FAKE_MCOUNT($bintr) /* init "from" bintr -> doreti */ doreti_next: From 5c40acf8b5d7dbe6ee052d93746ee65d1caf00e4 Mon Sep 17 00:00:00 2001 From: John Baldwin Date: Wed, 13 Apr 2016 18:39:33 +0000 Subject: [PATCH 002/143] Handle PBA that shares a page with MSI-X table for passthrough devices. If the PBA shares a page with the MSI-X table, map the shared page via /dev/mem and emulate accesses to the portion of the PBA in the shared page by accessing the mapped page. Reviewed by: grehan MFC after: 1 week Differential Revision: https://reviews.freebsd.org/D5919 --- usr.sbin/bhyve/pci_emul.h | 2 + usr.sbin/bhyve/pci_passthru.c | 117 ++++++++++++++++++++++++++++++---- 2 files changed, 105 insertions(+), 14 deletions(-) diff --git a/usr.sbin/bhyve/pci_emul.h b/usr.sbin/bhyve/pci_emul.h index 6b8c4e0fd31c..d6e549018b9f 100644 --- a/usr.sbin/bhyve/pci_emul.h +++ b/usr.sbin/bhyve/pci_emul.h @@ -142,6 +142,8 @@ struct pci_devinst { int pba_size; int function_mask; struct msix_table_entry *table; /* allocated at runtime */ + void *pba_page; + int pba_page_offset; } pi_msix; void *pi_arg; /* devemu-private data */ diff --git a/usr.sbin/bhyve/pci_passthru.c b/usr.sbin/bhyve/pci_passthru.c index 5b52b05b5998..66d31a2c4ebc 100644 --- a/usr.sbin/bhyve/pci_passthru.c +++ b/usr.sbin/bhyve/pci_passthru.c @@ -31,6 +31,7 @@ __FBSDID("$FreeBSD$"); #include #include +#include #include #include @@ -59,6 +60,10 @@ __FBSDID("$FreeBSD$"); #define _PATH_DEVIO "/dev/io" #endif +#ifndef _PATH_MEM +#define _PATH_MEM "/dev/mem" +#endif + #define LEGACY_SUPPORT 1 #define MSIX_TABLE_COUNT(ctrl) (((ctrl) & PCIM_MSIXCTRL_TABLE_SIZE) + 1) @@ -66,6 +71,7 @@ __FBSDID("$FreeBSD$"); static int pcifd = -1; static int iofd = -1; +static int memfd = -1; struct passthru_softc { struct pci_devinst *psc_pi; @@ -279,6 +285,35 @@ msix_table_read(struct passthru_softc *sc, uint64_t offset, int size) int index; pi = sc->psc_pi; + if (offset >= pi->pi_msix.pba_offset && + offset < pi->pi_msix.pba_offset + pi->pi_msix.pba_size) { + switch(size) { + case 1: + src8 = (uint8_t *)(pi->pi_msix.pba_page + offset - + pi->pi_msix.pba_page_offset); + data = *src8; + break; + case 2: + src16 = (uint16_t *)(pi->pi_msix.pba_page + offset - + pi->pi_msix.pba_page_offset); + data = *src16; + break; + case 4: + src32 = (uint32_t *)(pi->pi_msix.pba_page + offset - + pi->pi_msix.pba_page_offset); + data = *src32; + break; + case 8: + src64 = (uint64_t *)(pi->pi_msix.pba_page + offset - + pi->pi_msix.pba_page_offset); + data = *src64; + break; + default: + return (-1); + } + return (data); + } + if (offset < pi->pi_msix.table_offset) return (-1); @@ -320,12 +355,44 @@ msix_table_write(struct vmctx *ctx, int vcpu, struct passthru_softc *sc, { struct pci_devinst *pi; struct msix_table_entry *entry; - uint32_t *dest; + uint8_t *dest8; + uint16_t *dest16; + uint32_t *dest32; + uint64_t *dest64; size_t entry_offset; uint32_t vector_control; int error, index; pi = sc->psc_pi; + if (offset >= pi->pi_msix.pba_offset && + offset < pi->pi_msix.pba_offset + pi->pi_msix.pba_size) { + switch(size) { + case 1: + dest8 = (uint8_t *)(pi->pi_msix.pba_page + offset - + pi->pi_msix.pba_page_offset); + *dest8 = data; + break; + case 2: + dest16 = (uint16_t *)(pi->pi_msix.pba_page + offset - + pi->pi_msix.pba_page_offset); + *dest16 = data; + break; + case 4: + dest32 = (uint32_t *)(pi->pi_msix.pba_page + offset - + pi->pi_msix.pba_page_offset); + *dest32 = data; + break; + case 8: + dest64 = (uint64_t *)(pi->pi_msix.pba_page + offset - + pi->pi_msix.pba_page_offset); + *dest64 = data; + break; + default: + break; + } + return; + } + if (offset < pi->pi_msix.table_offset) return; @@ -342,8 +409,8 @@ msix_table_write(struct vmctx *ctx, int vcpu, struct passthru_softc *sc, assert(entry_offset % 4 == 0); vector_control = entry->vector_control; - dest = (uint32_t *)((void *)entry + entry_offset); - *dest = data; + dest32 = (uint32_t *)((void *)entry + entry_offset); + *dest32 = data; /* If MSI-X hasn't been enabled, do nothing */ if (pi->pi_msix.enabled) { /* If the entry is masked, don't set it up */ @@ -386,28 +453,44 @@ init_msix_table(struct vmctx *ctx, struct passthru_softc *sc, uint64_t base) table_size += pi->pi_msix.table_count * MSIX_TABLE_ENTRY_SIZE; table_size = roundup2(table_size, 4096); + idx = pi->pi_msix.table_bar; + start = pi->pi_bar[idx].addr; + remaining = pi->pi_bar[idx].size; + if (pi->pi_msix.pba_bar == pi->pi_msix.table_bar) { pba_offset = pi->pi_msix.pba_offset; pba_size = pi->pi_msix.pba_size; if (pba_offset >= table_offset + table_size || table_offset >= pba_offset + pba_size) { /* - * The PBA can reside in the same BAR as the MSI-x - * tables as long as it does not overlap with any - * naturally aligned page occupied by the tables. + * If the PBA does not share a page with the MSI-x + * tables, no PBA emulation is required. */ + pi->pi_msix.pba_page = NULL; + pi->pi_msix.pba_page_offset = 0; } else { - /* Need to also emulate the PBA, not supported yet */ - printf("Unsupported MSI-X configuration: %d/%d/%d\n", - b, s, f); - return (-1); + /* + * The PBA overlaps with either the first or last + * page of the MSI-X table region. Map the + * appropriate page. + */ + if (pba_offset <= table_offset) + pi->pi_msix.pba_page_offset = table_offset; + else + pi->pi_msix.pba_page_offset = table_offset + + table_size - 4096; + pi->pi_msix.pba_page = mmap(NULL, 4096, PROT_READ | + PROT_WRITE, MAP_SHARED, memfd, start + + pi->pi_msix.pba_page_offset); + if (pi->pi_msix.pba_page == MAP_FAILED) { + printf( + "Failed to map PBA page for MSI-X on %d/%d/%d: %s\n", + b, s, f, strerror(errno)); + return (-1); + } } } - idx = pi->pi_msix.table_bar; - start = pi->pi_bar[idx].addr; - remaining = pi->pi_bar[idx].size; - /* Map everything before the MSI-X table */ if (table_offset > 0) { len = table_offset; @@ -572,6 +655,12 @@ passthru_init(struct vmctx *ctx, struct pci_devinst *pi, char *opts) goto done; } + if (memfd < 0) { + memfd = open(_PATH_MEM, O_RDWR, 0); + if (memfd < 0) + goto done; + } + if (opts == NULL || sscanf(opts, "%d/%d/%d", &bus, &slot, &func) != 3) goto done; From c9767ca834512e8a10dbb6f4bc2cf1c6c322556d Mon Sep 17 00:00:00 2001 From: Scott Long Date: Wed, 13 Apr 2016 20:10:06 +0000 Subject: [PATCH 003/143] Add sbuf variants ata_cmd_sbuf() and ata_res_sbuf(), and reimplement the _string variants on top of this. This requires a change to the function signature of ata_res_sbuf(). Its use in the tree seems to be very limited, and the change makes it more consistent with the rest of the API. Reviewed by: imp, mav, kenm Sponsored by: Netflix Differential Revision: D5940 --- sys/cam/ata/ata_all.c | 66 ++++++++++++++++++++++++++++--------------- sys/cam/ata/ata_all.h | 3 +- sys/cam/cam.c | 3 +- 3 files changed, 47 insertions(+), 25 deletions(-) diff --git a/sys/cam/ata/ata_all.c b/sys/cam/ata/ata_all.c index d5220e874c78..51231b7bbd78 100644 --- a/sys/cam/ata/ata_all.c +++ b/sys/cam/ata/ata_all.c @@ -211,29 +211,64 @@ ata_op_string(struct ata_cmd *cmd) char * ata_cmd_string(struct ata_cmd *cmd, char *cmd_string, size_t len) { + struct sbuf sb; + int error; - snprintf(cmd_string, len, "%02x %02x %02x %02x " + if (len == 0) + return (""); + + sbuf_new(&sb, cmd_string, len, SBUF_FIXEDLEN); + ata_cmd_sbuf(cmd, &sb); + + error = sbuf_finish(&sb); + if (error != 0 && error != ENOMEM) + return (""); + + return(sbuf_data(&sb)); +} + +void +ata_cmd_sbuf(struct ata_cmd *cmd, struct sbuf *sb) +{ + sbuf_printf(sb, "%02x %02x %02x %02x " "%02x %02x %02x %02x %02x %02x %02x %02x", cmd->command, cmd->features, cmd->lba_low, cmd->lba_mid, cmd->lba_high, cmd->device, cmd->lba_low_exp, cmd->lba_mid_exp, cmd->lba_high_exp, cmd->features_exp, cmd->sector_count, cmd->sector_count_exp); - - return(cmd_string); } char * ata_res_string(struct ata_res *res, char *res_string, size_t len) { + struct sbuf sb; + int error; - snprintf(res_string, len, "%02x %02x %02x %02x " + if (len == 0) + return (""); + + sbuf_new(&sb, res_string, len, SBUF_FIXEDLEN); + ata_res_sbuf(res, &sb); + + error = sbuf_finish(&sb); + if (error != 0 && error != ENOMEM) + return (""); + + return(sbuf_data(&sb)); +} + +int +ata_res_sbuf(struct ata_res *res, struct sbuf *sb) +{ + + sbuf_printf(sb, "%02x %02x %02x %02x " "%02x %02x %02x %02x %02x %02x %02x", res->status, res->error, res->lba_low, res->lba_mid, res->lba_high, res->device, res->lba_low_exp, res->lba_mid_exp, res->lba_high_exp, res->sector_count, res->sector_count_exp); - return(res_string); + return (0); } /* @@ -242,11 +277,10 @@ ata_res_string(struct ata_res *res, char *res_string, size_t len) int ata_command_sbuf(struct ccb_ataio *ataio, struct sbuf *sb) { - char cmd_str[(12 * 3) + 1]; - sbuf_printf(sb, "%s. ACB: %s", - ata_op_string(&ataio->cmd), - ata_cmd_string(&ataio->cmd, cmd_str, sizeof(cmd_str))); + sbuf_printf(sb, "%s. ACB: ", + ata_op_string(&ataio->cmd)); + ata_cmd_sbuf(&ataio->cmd, sb); return(0); } @@ -284,20 +318,6 @@ ata_status_sbuf(struct ccb_ataio *ataio, struct sbuf *sb) return(0); } -/* - * ata_res_sbuf() returns 0 for success and -1 for failure. - */ -int -ata_res_sbuf(struct ccb_ataio *ataio, struct sbuf *sb) -{ - char res_str[(11 * 3) + 1]; - - sbuf_printf(sb, "RES: %s", - ata_res_string(&ataio->res, res_str, sizeof(res_str))); - - return(0); -} - void ata_print_ident(struct ata_params *ident_data) { diff --git a/sys/cam/ata/ata_all.h b/sys/cam/ata/ata_all.h index 91e941c8f757..433c61c5a6c1 100644 --- a/sys/cam/ata/ata_all.h +++ b/sys/cam/ata/ata_all.h @@ -103,10 +103,11 @@ int ata_version(int ver); char * ata_op_string(struct ata_cmd *cmd); char * ata_cmd_string(struct ata_cmd *cmd, char *cmd_string, size_t len); +void ata_cmd_sbuf(struct ata_cmd *cmd, struct sbuf *sb); char * ata_res_string(struct ata_res *res, char *res_string, size_t len); int ata_command_sbuf(struct ccb_ataio *ataio, struct sbuf *sb); int ata_status_sbuf(struct ccb_ataio *ataio, struct sbuf *sb); -int ata_res_sbuf(struct ccb_ataio *ataio, struct sbuf *sb); +int ata_res_sbuf(struct ata_res *res, struct sbuf *sb); void ata_print_ident(struct ata_params *ident_data); void ata_print_ident_short(struct ata_params *ident_data); diff --git a/sys/cam/cam.c b/sys/cam/cam.c index 1f627ef1e63c..5061dd67ac74 100644 --- a/sys/cam/cam.c +++ b/sys/cam/cam.c @@ -412,7 +412,8 @@ cam_error_string(struct cam_device *device, union ccb *ccb, char *str, } if (proto_flags & CAM_EAF_PRINT_RESULT) { sbuf_cat(&sb, path_str); - ata_res_sbuf(&ccb->ataio, &sb); + sbuf_printf(&sb, "RES: "); + ata_res_sbuf(&ccb->ataio.res, &sb); sbuf_printf(&sb, "\n"); } From cc7b259a263c0fc419328994779ce66bff5abe7d Mon Sep 17 00:00:00 2001 From: Jamie Gritton Date: Wed, 13 Apr 2016 20:14:13 +0000 Subject: [PATCH 004/143] Separate POSIX sem/shm objects in jails, by prepending the jail's path name to the object's "path". While the objects don't have real path names, it's a filesystem-like namespace, which allows jails to be kept to their own space, but still allows the system / jail parent to access a jail's IPC. PR: 208082 --- sys/kern/uipc_sem.c | 36 ++++++++++++++++++++++++++++++++---- sys/kern/uipc_shm.c | 37 ++++++++++++++++++++++++++++++++----- 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/sys/kern/uipc_sem.c b/sys/kern/uipc_sem.c index 1b2c7615d44b..efaf1e03033f 100644 --- a/sys/kern/uipc_sem.c +++ b/sys/kern/uipc_sem.c @@ -44,6 +44,7 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include #include #include #include @@ -258,7 +259,9 @@ ksem_closef(struct file *fp, struct thread *td) static int ksem_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) { + const char *path, *pr_path; struct ksem *ks; + size_t pr_pathlen; kif->kf_type = KF_TYPE_SEM; ks = fp->f_data; @@ -269,7 +272,19 @@ ksem_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) if (ks->ks_path != NULL) { sx_slock(&ksem_dict_lock); if (ks->ks_path != NULL) - strlcpy(kif->kf_path, ks->ks_path, sizeof(kif->kf_path)); + { + path = ks->ks_path; + pr_path = curthread->td_ucred->cr_prison->pr_path; + if (strcmp(pr_path, "/") != 0) + { + /* Return the jail-rooted pathname */ + pr_pathlen = strlen(pr_path); + if (strncmp(path, pr_path, pr_pathlen) == 0 && + path[pr_pathlen] == '/') + path += pr_pathlen; + } + strlcpy(kif->kf_path, path, sizeof(kif->kf_path)); + } sx_sunlock(&ksem_dict_lock); } return (0); @@ -449,6 +464,8 @@ ksem_create(struct thread *td, const char *name, semid_t *semidp, mode_t mode, struct ksem *ks; struct file *fp; char *path; + const char *pr_path; + size_t pr_pathlen; Fnv32_t fnv; int error, fd; @@ -485,10 +502,15 @@ ksem_create(struct thread *td, const char *name, semid_t *semidp, mode_t mode, ks->ks_flags |= KS_ANONYMOUS; } else { path = malloc(MAXPATHLEN, M_KSEM, M_WAITOK); - error = copyinstr(name, path, MAXPATHLEN, NULL); + pr_path = td->td_ucred->cr_prison->pr_path; + /* Construct a full pathname for jailed callers */ + pr_pathlen = strcmp(pr_path, "/") == 0 ? 0 + : strlcpy(path, pr_path, MAXPATHLEN); + error = copyinstr(name, path + pr_pathlen, + MAXPATHLEN - pr_pathlen, NULL); /* Require paths to start with a '/' character. */ - if (error == 0 && path[0] != '/') + if (error == 0 && path[pr_pathlen] != '/') error = EINVAL; if (error) { fdclose(td, fp, fd); @@ -624,11 +646,17 @@ int sys_ksem_unlink(struct thread *td, struct ksem_unlink_args *uap) { char *path; + const char *pr_path; + size_t pr_pathlen; Fnv32_t fnv; int error; path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK); - error = copyinstr(uap->name, path, MAXPATHLEN, NULL); + pr_path = td->td_ucred->cr_prison->pr_path; + pr_pathlen = strcmp(pr_path, "/") == 0 ? 0 + : strlcpy(path, pr_path, MAXPATHLEN); + error = copyinstr(uap->name, path + pr_pathlen, MAXPATHLEN - pr_pathlen, + NULL); if (error) { free(path, M_TEMP); return (error); diff --git a/sys/kern/uipc_shm.c b/sys/kern/uipc_shm.c index a2146b99cc3e..3d78dc4e99bb 100644 --- a/sys/kern/uipc_shm.c +++ b/sys/kern/uipc_shm.c @@ -57,6 +57,7 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include #include #include #include @@ -687,6 +688,8 @@ kern_shm_open(struct thread *td, const char *userpath, int flags, mode_t mode, struct shmfd *shmfd; struct file *fp; char *path; + const char *pr_path; + size_t pr_pathlen; Fnv32_t fnv; mode_t cmode; int fd, error; @@ -723,13 +726,18 @@ kern_shm_open(struct thread *td, const char *userpath, int flags, mode_t mode, shmfd = shm_alloc(td->td_ucred, cmode); } else { path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK); - error = copyinstr(userpath, path, MAXPATHLEN, NULL); + pr_path = td->td_ucred->cr_prison->pr_path; + /* Construct a full pathname for jailed callers */ + pr_pathlen = strcmp(pr_path, "/") == 0 ? 0 + : strlcpy(path, pr_path, MAXPATHLEN); + error = copyinstr(userpath, path + pr_pathlen, + MAXPATHLEN - pr_pathlen, NULL); #ifdef KTRACE if (error == 0 && KTRPOINT(curthread, KTR_NAMEI)) ktrnamei(path); #endif /* Require paths to start with a '/' character. */ - if (error == 0 && path[0] != '/') + if (error == 0 && path[pr_pathlen] != '/') error = EINVAL; if (error) { fdclose(td, fp, fd); @@ -823,11 +831,17 @@ int sys_shm_unlink(struct thread *td, struct shm_unlink_args *uap) { char *path; + const char *pr_path; + size_t pr_pathlen; Fnv32_t fnv; int error; path = malloc(MAXPATHLEN, M_TEMP, M_WAITOK); - error = copyinstr(uap->path, path, MAXPATHLEN, NULL); + pr_path = td->td_ucred->cr_prison->pr_path; + pr_pathlen = strcmp(pr_path, "/") == 0 ? 0 + : strlcpy(path, pr_path, MAXPATHLEN); + error = copyinstr(uap->path, path + pr_pathlen, MAXPATHLEN - pr_pathlen, + NULL); if (error) { free(path, M_TEMP); return (error); @@ -1060,7 +1074,9 @@ shm_unmap(struct file *fp, void *mem, size_t size) static int shm_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) { + const char *path, *pr_path; struct shmfd *shmfd; + size_t pr_pathlen; kif->kf_type = KF_TYPE_SHM; shmfd = fp->f_data; @@ -1072,8 +1088,19 @@ shm_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) if (shmfd->shm_path != NULL) { sx_slock(&shm_dict_lock); if (shmfd->shm_path != NULL) - strlcpy(kif->kf_path, shmfd->shm_path, - sizeof(kif->kf_path)); + { + path = shmfd->shm_path; + pr_path = curthread->td_ucred->cr_prison->pr_path; + if (strcmp(pr_path, "/") != 0) + { + /* Return the jail-rooted pathname */ + pr_pathlen = strlen(pr_path); + if (strncmp(path, pr_path, pr_pathlen) == 0 && + path[pr_pathlen] == '/') + path += pr_pathlen; + } + strlcpy(kif->kf_path, path, sizeof(kif->kf_path)); + } sx_sunlock(&shm_dict_lock); } return (0); From adb023ae59d5535b8288fb779fd6e24b96cbd8ca Mon Sep 17 00:00:00 2001 From: Jamie Gritton Date: Wed, 13 Apr 2016 20:15:49 +0000 Subject: [PATCH 005/143] Separate POSIX mqueue objects in jails; actually, separate them by the jail's root, so jails that don't have their own filesystem directory also won't have their own mqueue namespace. PR: 208082 --- sys/kern/uipc_mqueue.c | 125 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 119 insertions(+), 6 deletions(-) diff --git a/sys/kern/uipc_mqueue.c b/sys/kern/uipc_mqueue.c index 0589f4adf4f4..ecc9bcfef95f 100644 --- a/sys/kern/uipc_mqueue.c +++ b/sys/kern/uipc_mqueue.c @@ -52,6 +52,7 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include #include #include #include @@ -60,8 +61,8 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include #include -#include #include #include #include @@ -132,6 +133,7 @@ struct mqfs_node { LIST_HEAD(,mqfs_node) mn_children; LIST_ENTRY(mqfs_node) mn_sibling; LIST_HEAD(,mqfs_vdata) mn_vnodes; + const void *mn_pr_root; int mn_refcount; mqfs_type_t mn_type; int mn_deleted; @@ -152,6 +154,11 @@ struct mqfs_node { #define FPTOMQ(fp) ((struct mqueue *)(((struct mqfs_node *) \ (fp)->f_data)->mn_data)) +struct mqfs_osd { + struct task mo_task; + const void *mo_pr_root; +}; + TAILQ_HEAD(msgq, mqueue_msg); struct mqueue; @@ -219,6 +226,7 @@ static uma_zone_t mvdata_zone; static uma_zone_t mqnoti_zone; static struct vop_vector mqfs_vnodeops; static struct fileops mqueueops; +static unsigned mqfs_osd_jail_slot; /* * Directory structure construction and manipulation @@ -236,6 +244,9 @@ static int mqfs_destroy(struct mqfs_node *mn); static void mqfs_fileno_alloc(struct mqfs_info *mi, struct mqfs_node *mn); static void mqfs_fileno_free(struct mqfs_info *mi, struct mqfs_node *mn); static int mqfs_allocv(struct mount *mp, struct vnode **vpp, struct mqfs_node *pn); +static int mqfs_prison_create(void *obj, void *data); +static void mqfs_prison_destructor(void *data); +static void mqfs_prison_remove_task(void *context, int pending); /* * Message queue construction and maniplation @@ -436,6 +447,7 @@ mqfs_create_node(const char *name, int namelen, struct ucred *cred, int mode, node = mqnode_alloc(); strncpy(node->mn_name, name, namelen); + node->mn_pr_root = cred->cr_prison->pr_root; node->mn_type = nodetype; node->mn_refcount = 1; vfs_timestamp(&node->mn_birth); @@ -644,6 +656,10 @@ mqfs_init(struct vfsconf *vfc) { struct mqfs_node *root; struct mqfs_info *mi; + struct prison *pr; + osd_method_t methods[PR_MAXMETHOD] = { + [PR_METHOD_CREATE] = mqfs_prison_create, + }; mqnode_zone = uma_zcreate("mqnode", sizeof(struct mqfs_node), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); @@ -670,6 +686,12 @@ mqfs_init(struct vfsconf *vfc) EVENTHANDLER_PRI_ANY); mq_fdclose = mqueue_fdclose; p31b_setcfg(CTL_P1003_1B_MESSAGE_PASSING, _POSIX_MESSAGE_PASSING); + /* Note current jails */ + mqfs_osd_jail_slot = osd_jail_register(mqfs_prison_destructor, methods); + sx_slock(&allprison_lock); + TAILQ_FOREACH(pr, &allprison, pr_list) + (void)mqfs_prison_create(pr, NULL); + sx_sunlock(&allprison_lock); return (0); } @@ -679,10 +701,14 @@ mqfs_init(struct vfsconf *vfc) static int mqfs_uninit(struct vfsconf *vfc) { + unsigned slot; struct mqfs_info *mi; if (!unloadable) return (EOPNOTSUPP); + slot = mqfs_osd_jail_slot; + mqfs_osd_jail_slot = 0; + osd_jail_deregister(slot); EVENTHANDLER_DEREGISTER(process_exit, exit_tag); mi = &mqfs_data; mqfs_destroy(mi->mi_root); @@ -800,13 +826,17 @@ mqfs_allocv(struct mount *mp, struct vnode **vpp, struct mqfs_node *pn) * Search a directory entry */ static struct mqfs_node * -mqfs_search(struct mqfs_node *pd, const char *name, int len) +mqfs_search(struct mqfs_node *pd, const char *name, int len, struct ucred *cred) { struct mqfs_node *pn; + const void *pr_root; sx_assert(&pd->mn_info->mi_lock, SX_LOCKED); + pr_root = cred->cr_prison->pr_root; LIST_FOREACH(pn, &pd->mn_children, mn_sibling) { - if (strncmp(pn->mn_name, name, len) == 0 && + /* Only match names within the same prison root directory */ + if ((pn->mn_pr_root == NULL || pn->mn_pr_root == pr_root) && + strncmp(pn->mn_name, name, len) == 0 && pn->mn_name[len] == '\0') return (pn); } @@ -878,7 +908,7 @@ mqfs_lookupx(struct vop_cachedlookup_args *ap) /* named node */ sx_xlock(&mqfs->mi_lock); - pn = mqfs_search(pd, pname, namelen); + pn = mqfs_search(pd, pname, namelen, cnp->cn_cred); if (pn != NULL) mqnode_addref(pn); sx_xunlock(&mqfs->mi_lock); @@ -1363,6 +1393,7 @@ mqfs_readdir(struct vop_readdir_args *ap) struct mqfs_node *pn; struct dirent entry; struct uio *uio; + const void *pr_root; int *tmp_ncookies = NULL; off_t offset; int error, i; @@ -1387,10 +1418,17 @@ mqfs_readdir(struct vop_readdir_args *ap) error = 0; offset = 0; + pr_root = ap->a_cred->cr_prison->pr_root; sx_xlock(&mi->mi_lock); LIST_FOREACH(pn, &pd->mn_children, mn_sibling) { entry.d_reclen = sizeof(entry); + /* + * Only show names within the same prison root directory + * (or not associated with a prison, e.g. "." and ".."). + */ + if (pn->mn_pr_root != NULL && pn->mn_pr_root != pr_root) + continue; if (!pn->mn_fileno) mqfs_fileno_alloc(mi, pn); entry.d_fileno = pn->mn_fileno; @@ -1523,6 +1561,81 @@ mqfs_rmdir(struct vop_rmdir_args *ap) #endif /* notyet */ + +/* + * Set a destructor task with the prison's root + */ +static int +mqfs_prison_create(void *obj, void *data __unused) +{ + struct prison *pr = obj; + struct mqfs_osd *mo; + void *rsv; + + if (pr->pr_root == pr->pr_parent->pr_root) + return(0); + + mo = malloc(sizeof(struct mqfs_osd), M_PRISON, M_WAITOK); + rsv = osd_reserve(mqfs_osd_jail_slot); + TASK_INIT(&mo->mo_task, 0, mqfs_prison_remove_task, mo); + mtx_lock(&pr->pr_mtx); + mo->mo_pr_root = pr->pr_root; + (void)osd_jail_set_reserved(pr, mqfs_osd_jail_slot, rsv, mo); + mtx_unlock(&pr->pr_mtx); + return (0); +} + +/* + * Queue the task for after jail/OSD locks are released + */ +static void +mqfs_prison_destructor(void *data) +{ + struct mqfs_osd *mo = data; + + if (mqfs_osd_jail_slot != 0) + taskqueue_enqueue(taskqueue_thread, &mo->mo_task); + else + free(mo, M_PRISON); +} + +/* + * See if this prison root is obsolete, and clean up associated queues if it is + */ +static void +mqfs_prison_remove_task(void *context, int pending) +{ + struct mqfs_osd *mo = context; + struct mqfs_node *pn, *tpn; + const struct prison *pr; + const void *pr_root; + int found; + + pr_root = mo->mo_pr_root; + found = 0; + sx_slock(&allprison_lock); + TAILQ_FOREACH(pr, &allprison, pr_list) { + if (pr->pr_root == pr_root) + found = 1; + } + sx_sunlock(&allprison_lock); + if (!found) { + /* + * No jails are rooted in this directory anymore, + * so no queues should be either. + */ + sx_xlock(&mqfs_data.mi_lock); + LIST_FOREACH_SAFE(pn, &mqfs_data.mi_root->mn_children, + mn_sibling, tpn) { + if (pn->mn_pr_root == pr_root) + (void)do_unlink(pn, curthread->td_ucred); + } + sx_xunlock(&mqfs_data.mi_lock); + } + free(mo, M_PRISON); +} + + /* * Allocate a message queue */ @@ -1983,7 +2096,7 @@ kern_kmq_open(struct thread *td, const char *upath, int flags, mode_t mode, return (error); sx_xlock(&mqfs_data.mi_lock); - pn = mqfs_search(mqfs_data.mi_root, path + 1, len - 1); + pn = mqfs_search(mqfs_data.mi_root, path + 1, len - 1, td->td_ucred); if (pn == NULL) { if (!(flags & O_CREAT)) { error = ENOENT; @@ -2078,7 +2191,7 @@ sys_kmq_unlink(struct thread *td, struct kmq_unlink_args *uap) return (EINVAL); sx_xlock(&mqfs_data.mi_lock); - pn = mqfs_search(mqfs_data.mi_root, path + 1, len - 1); + pn = mqfs_search(mqfs_data.mi_root, path + 1, len - 1, td->td_ucred); if (pn != NULL) error = do_unlink(pn, td->td_ucred); else From d72505899b0caf6da985c4153e992604001f6c60 Mon Sep 17 00:00:00 2001 From: Jilles Tjoelker Date: Wed, 13 Apr 2016 20:32:35 +0000 Subject: [PATCH 006/143] sh: Simplify code by removing variable bracketed_name. --- bin/sh/parser.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/bin/sh/parser.c b/bin/sh/parser.c index 3f9732cbbff3..e72a6f1c7e2e 100644 --- a/bin/sh/parser.c +++ b/bin/sh/parser.c @@ -1616,7 +1616,6 @@ parsesub: { int flags; char *p; static const char types[] = "}-+?="; - int bracketed_name = 0; /* used to handle ${[0-9]*} variables */ int linno; int length; int c1; @@ -1640,7 +1639,6 @@ parsesub: { subtype = VSNORMAL; flags = 0; if (c == '{') { - bracketed_name = 1; c = pgetc_linecont(); subtype = 0; } @@ -1665,7 +1663,7 @@ parsesub: { flags |= VSLINENO; } } else if (is_digit(c)) { - if (bracketed_name) { + if (subtype != VSNORMAL) { do { STPUTC(c, out); c = pgetc_linecont(); From 01d57ec0662c7b1c4af4bf0d944565e855374819 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Wed, 13 Apr 2016 20:43:02 +0000 Subject: [PATCH 007/143] Remove misspelled and redundant MK_INSTALLIB=no. --- release/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release/Makefile b/release/Makefile index ba1ca80c050c..a8efa2c26150 100644 --- a/release/Makefile +++ b/release/Makefile @@ -200,7 +200,7 @@ bootonly: packagesystem MK_GAMES=no MK_GROFF=no \ MK_INSTALLLIB=no MK_LIB32=no MK_MAIL=no \ MK_NCP=no MK_TOOLCHAIN=no MK_PROFILE=no \ - MK_INSTALLIB=no MK_RESCUE=no MK_DICT=no \ + MK_RESCUE=no MK_DICT=no \ MK_KERNEL_SYMBOLS=no MK_TESTS=no MK_DEBUG_FILES=no # Copy manifest only (no distfiles) to get checksums mkdir -p ${.TARGET}/usr/freebsd-dist From e52a5f2496dd3869abfeb3c03bf00668fb812ecf Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Wed, 13 Apr 2016 20:55:05 +0000 Subject: [PATCH 008/143] The build does work now with WITHOUT_TOOLCHAIN. The bootstrap cross tools are still built in this mode as well. Sponsored by: EMC / Isilon Storage Division --- tools/build/options/WITHOUT_TOOLCHAIN | 3 --- 1 file changed, 3 deletions(-) diff --git a/tools/build/options/WITHOUT_TOOLCHAIN b/tools/build/options/WITHOUT_TOOLCHAIN index 2aa4217400f6..b45f2f3acceb 100644 --- a/tools/build/options/WITHOUT_TOOLCHAIN +++ b/tools/build/options/WITHOUT_TOOLCHAIN @@ -2,6 +2,3 @@ Set to not install header or programs used for program development, compilers, debuggers etc. -.Bf -symbolic -The option does not work for build targets. -.Ef From 6b580fd720344025c05bfc2f8e56efacce3fd2cd Mon Sep 17 00:00:00 2001 From: Ed Maste Date: Wed, 13 Apr 2016 21:00:00 +0000 Subject: [PATCH 009/143] arm64: Avoid null dereference in its_init_cpu its_init_cpu() is called from gic_v3_init_secondary(), and its_sc will be NULL if its did not attach. Sponsored by: The FreeBSD Foundation --- sys/arm64/arm64/gic_v3_its.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/arm64/arm64/gic_v3_its.c b/sys/arm64/arm64/gic_v3_its.c index aef6346e6e9b..c830c99cab98 100644 --- a/sys/arm64/arm64/gic_v3_its.c +++ b/sys/arm64/arm64/gic_v3_its.c @@ -565,7 +565,7 @@ its_init_cpu(struct gic_v3_its_softc *sc) * this function was called during GICv3 secondary initialization. */ if (sc == NULL) { - if (device_is_attached(its_sc->dev)) { + if (its_sc != NULL && device_is_attached(its_sc->dev)) { /* * XXX ARM64TODO: This is part of the workaround that * saves ITS software context for further use in From 361c75321b30cb78c342c953b08f1e83817fcbf9 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Wed, 13 Apr 2016 21:01:58 +0000 Subject: [PATCH 010/143] Note the brokenness of WITHOUT_INSTALLLIB. Sponsored by: EMC / Isilon Storage Division --- tools/build/options/WITHOUT_INSTALLLIB | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/build/options/WITHOUT_INSTALLLIB b/tools/build/options/WITHOUT_INSTALLLIB index bfd313fedfdd..e2aba1363f4f 100644 --- a/tools/build/options/WITHOUT_INSTALLLIB +++ b/tools/build/options/WITHOUT_INSTALLLIB @@ -3,3 +3,6 @@ Set this if you do not want to install optional libraries. For example when creating a .Xr nanobsd 8 image. +.Bf -symbolic +The option does not work for build targets. +.Ef From 6baf7cc80ea9cb47434833c387c09cacfd248571 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Wed, 13 Apr 2016 21:08:02 +0000 Subject: [PATCH 011/143] libgssapi: avoid NULL pointer dereferences. While here also use NULL instead of zero for pointers. Found with coccinelle. MFC after: 1 week --- lib/libgssapi/gss_add_cred.c | 4 ++-- lib/libgssapi/gss_encapsulate_token.c | 2 +- lib/libgssapi/gss_get_mic.c | 3 ++- lib/libgssapi/gss_inquire_context.c | 2 +- lib/libgssapi/gss_mech_switch.c | 2 +- lib/libgssapi/gss_pseudo_random.c | 3 ++- lib/libgssapi/gss_verify_mic.c | 3 ++- lib/libgssapi/gss_wrap.c | 3 ++- lib/libgssapi/gss_wrap_size_limit.c | 3 ++- 9 files changed, 15 insertions(+), 10 deletions(-) diff --git a/lib/libgssapi/gss_add_cred.c b/lib/libgssapi/gss_add_cred.c index 4dcca18a3251..34e29b1a2b71 100644 --- a/lib/libgssapi/gss_add_cred.c +++ b/lib/libgssapi/gss_add_cred.c @@ -121,7 +121,7 @@ gss_add_cred(OM_uint32 *minor_status, * gss_add_cred for that mechanism, otherwise we copy the mc * to new_cred. */ - target_mc = 0; + target_mc = NULL; if (cred) { SLIST_FOREACH(mc, &cred->gc_mc, gmc_link) { if (gss_oid_equal(mc->gmc_mech_oid, desired_mech)) { @@ -151,7 +151,7 @@ gss_add_cred(OM_uint32 *minor_status, return (major_status); } } else { - mn = 0; + mn = NULL; } m = _gss_find_mech_switch(desired_mech); diff --git a/lib/libgssapi/gss_encapsulate_token.c b/lib/libgssapi/gss_encapsulate_token.c index ed0e217d65be..0e33e191ec85 100644 --- a/lib/libgssapi/gss_encapsulate_token.c +++ b/lib/libgssapi/gss_encapsulate_token.c @@ -47,7 +47,7 @@ gss_encapsulate_token(const gss_buffer_t input_token, gss_OID oid, * First time around, we calculate the size, second time, we * encode the token. */ - p = 0; + p = NULL; for (i = 0; i < 2; i++) { len = 0; diff --git a/lib/libgssapi/gss_get_mic.c b/lib/libgssapi/gss_get_mic.c index dff3b545f78f..b55a796dedad 100644 --- a/lib/libgssapi/gss_get_mic.c +++ b/lib/libgssapi/gss_get_mic.c @@ -40,13 +40,14 @@ gss_get_mic(OM_uint32 *minor_status, gss_buffer_t message_token) { struct _gss_context *ctx = (struct _gss_context *) context_handle; - struct _gss_mech_switch *m = ctx->gc_mech; + struct _gss_mech_switch *m; _gss_buffer_zero(message_token); if (ctx == NULL) { *minor_status = 0; return (GSS_S_NO_CONTEXT); } + m = ctx->gc_mech; return (m->gm_get_mic(minor_status, ctx->gc_ctx, qop_req, message_buffer, message_token)); diff --git a/lib/libgssapi/gss_inquire_context.c b/lib/libgssapi/gss_inquire_context.c index c9f2a0c545ef..59e03e819284 100644 --- a/lib/libgssapi/gss_inquire_context.c +++ b/lib/libgssapi/gss_inquire_context.c @@ -99,7 +99,7 @@ gss_inquire_context(OM_uint32 *minor_status, if (src_name) gss_release_name(minor_status, src_name); m->gm_release_name(minor_status, &src_mn); - minor_status = 0; + minor_status = NULL; return (GSS_S_FAILURE); } *targ_name = (gss_name_t) name; diff --git a/lib/libgssapi/gss_mech_switch.c b/lib/libgssapi/gss_mech_switch.c index d07db8865d3f..2d742e7ee232 100644 --- a/lib/libgssapi/gss_mech_switch.c +++ b/lib/libgssapi/gss_mech_switch.c @@ -83,7 +83,7 @@ _gss_string_to_oid(const char* s, gss_OID oid) * out the size. Second time around, we actually encode the * number. */ - res = 0; + res = NULL; for (i = 0; i < 2; i++) { byte_count = 0; for (p = s, j = 0; p; p = q, j++) { diff --git a/lib/libgssapi/gss_pseudo_random.c b/lib/libgssapi/gss_pseudo_random.c index c250d717a62f..c74682329585 100644 --- a/lib/libgssapi/gss_pseudo_random.c +++ b/lib/libgssapi/gss_pseudo_random.c @@ -48,7 +48,7 @@ gss_pseudo_random(OM_uint32 *minor_status, gss_buffer_t prf_out) { struct _gss_context *ctx = (struct _gss_context *) context; - struct _gss_mech_switch *m = ctx->gc_mech; + struct _gss_mech_switch *m; OM_uint32 major_status; _gss_buffer_zero(prf_out); @@ -58,6 +58,7 @@ gss_pseudo_random(OM_uint32 *minor_status, *minor_status = 0; return GSS_S_NO_CONTEXT; } + m = ctx->gc_mech; if (m->gm_pseudo_random == NULL) return GSS_S_UNAVAILABLE; diff --git a/lib/libgssapi/gss_verify_mic.c b/lib/libgssapi/gss_verify_mic.c index fa3d68d035fe..704d7fcc2c78 100644 --- a/lib/libgssapi/gss_verify_mic.c +++ b/lib/libgssapi/gss_verify_mic.c @@ -39,7 +39,7 @@ gss_verify_mic(OM_uint32 *minor_status, gss_qop_t *qop_state) { struct _gss_context *ctx = (struct _gss_context *) context_handle; - struct _gss_mech_switch *m = ctx->gc_mech; + struct _gss_mech_switch *m; if (qop_state) *qop_state = 0; @@ -47,6 +47,7 @@ gss_verify_mic(OM_uint32 *minor_status, *minor_status = 0; return (GSS_S_NO_CONTEXT); } + m = ctx->gc_mech; return (m->gm_verify_mic(minor_status, ctx->gc_ctx, message_buffer, token_buffer, qop_state)); diff --git a/lib/libgssapi/gss_wrap.c b/lib/libgssapi/gss_wrap.c index 2f9431694a5f..1cf046ab86b6 100644 --- a/lib/libgssapi/gss_wrap.c +++ b/lib/libgssapi/gss_wrap.c @@ -42,7 +42,7 @@ gss_wrap(OM_uint32 *minor_status, gss_buffer_t output_message_buffer) { struct _gss_context *ctx = (struct _gss_context *) context_handle; - struct _gss_mech_switch *m = ctx->gc_mech; + struct _gss_mech_switch *m; if (conf_state) *conf_state = 0; @@ -51,6 +51,7 @@ gss_wrap(OM_uint32 *minor_status, *minor_status = 0; return (GSS_S_NO_CONTEXT); } + m = ctx->gc_mech; return (m->gm_wrap(minor_status, ctx->gc_ctx, conf_req_flag, qop_req, input_message_buffer, diff --git a/lib/libgssapi/gss_wrap_size_limit.c b/lib/libgssapi/gss_wrap_size_limit.c index 15a870676da4..7038a576e7c2 100644 --- a/lib/libgssapi/gss_wrap_size_limit.c +++ b/lib/libgssapi/gss_wrap_size_limit.c @@ -40,13 +40,14 @@ gss_wrap_size_limit(OM_uint32 *minor_status, OM_uint32 *max_input_size) { struct _gss_context *ctx = (struct _gss_context *) context_handle; - struct _gss_mech_switch *m = ctx->gc_mech; + struct _gss_mech_switch *m; *max_input_size = 0; if (ctx == NULL) { *minor_status = 0; return (GSS_S_NO_CONTEXT); } + m = ctx->gc_mech; return (m->gm_wrap_size_limit(minor_status, ctx->gc_ctx, conf_req_flag, qop_req, req_output_size, max_input_size)); From 2927e6a868606b44e71ae98a783b827383edb2e5 Mon Sep 17 00:00:00 2001 From: Oleksandr Tymoshenko Date: Wed, 13 Apr 2016 21:39:45 +0000 Subject: [PATCH 012/143] Fix UART3 and UART4 clock offsets. Original values were copy-pasted from UART1 and UART2 PR: 197037 Submitted by: Scott Ellis --- sys/arm/ti/omap4/omap4_prcm_clks.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sys/arm/ti/omap4/omap4_prcm_clks.c b/sys/arm/ti/omap4/omap4_prcm_clks.c index fc5fb975b76e..e83e6eeb1994 100644 --- a/sys/arm/ti/omap4/omap4_prcm_clks.c +++ b/sys/arm/ti/omap4/omap4_prcm_clks.c @@ -366,9 +366,9 @@ static struct omap4_clk_details g_omap4_clk_details[] = { OMAP4_GENERIC_CLOCK_DETAILS(UART2_CLK, FREQ_48MHZ, CM2_INSTANCE, (L4PER_CM2_OFFSET + 0x0148), CLKCTRL_MODULEMODE_ENABLE), OMAP4_GENERIC_CLOCK_DETAILS(UART3_CLK, FREQ_48MHZ, CM2_INSTANCE, - (L4PER_CM2_OFFSET + 0x0140), CLKCTRL_MODULEMODE_ENABLE), + (L4PER_CM2_OFFSET + 0x0150), CLKCTRL_MODULEMODE_ENABLE), OMAP4_GENERIC_CLOCK_DETAILS(UART4_CLK, FREQ_48MHZ, CM2_INSTANCE, - (L4PER_CM2_OFFSET + 0x0148), CLKCTRL_MODULEMODE_ENABLE), + (L4PER_CM2_OFFSET + 0x0158), CLKCTRL_MODULEMODE_ENABLE), /* General purpose timers */ OMAP4_GENERIC_CLOCK_DETAILS(TIMER1_CLK, -1, PRM_INSTANCE, From 2d57dc7e6e01f3e8166db91ab1be0cd8f19ef0f2 Mon Sep 17 00:00:00 2001 From: Navdeep Parhar Date: Thu, 14 Apr 2016 00:25:11 +0000 Subject: [PATCH 013/143] Send krping output to the log instead of the tty, as is done upstream. Reviewed by: hselasky@ Sponsored by: Chelsio Communications Differential Revision: https://reviews.freebsd.org/D5931 --- sys/contrib/rdma/krping/krping.c | 124 ++++++++++++++------------- sys/contrib/rdma/krping/krping.h | 1 - sys/contrib/rdma/krping/krping_dev.c | 10 --- 3 files changed, 63 insertions(+), 72 deletions(-) diff --git a/sys/contrib/rdma/krping/krping.c b/sys/contrib/rdma/krping/krping.c index 931f76015e01..8e91e2a0b011 100644 --- a/sys/contrib/rdma/krping/krping.c +++ b/sys/contrib/rdma/krping/krping.c @@ -54,8 +54,8 @@ __FBSDID("$FreeBSD$"); #include "getopt.h" extern int krping_debug; -#define DEBUG_LOG(cb, x...) if (krping_debug) krping_printf((cb)->cookie, x) -#define PRINTF(cb, x...) krping_printf((cb)->cookie, x) +#define DEBUG_LOG(cb, x...) if (krping_debug) log(LOG_INFO, x) +#define PRINTF(cb, x...) log(LOG_INFO, x) #define BIND_INFO 1 MODULE_AUTHOR("Steve Wise"); @@ -376,8 +376,8 @@ static void krping_cq_event_handler(struct ib_cq *cq, void *ctx) continue; } else { PRINTF(cb, "cq completion failed with " - "wr_id %Lx status %d opcode %d vender_err %x\n", - wc.wr_id, wc.status, wc.opcode, wc.vendor_err); + "wr_id %jx status %d opcode %d vender_err %x\n", + (uintmax_t)wc.wr_id, wc.status, wc.opcode, wc.vendor_err); goto error; } } @@ -570,8 +570,8 @@ static int krping_setup_buffers(struct krping_cb *cb) if (!cb->local_dma_lkey) { buf.addr = cb->recv_dma_addr; buf.size = sizeof cb->recv_buf; - DEBUG_LOG(cb, "recv buf dma_addr %llx size %d\n", buf.addr, - (int)buf.size); + DEBUG_LOG(cb, "recv buf dma_addr %jx size %d\n", + (uintmax_t)buf.addr, (int)buf.size); iovbase = cb->recv_dma_addr; cb->recv_mr = ib_reg_phys_mr(cb->pd, &buf, 1, IB_ACCESS_LOCAL_WRITE, @@ -585,8 +585,8 @@ static int krping_setup_buffers(struct krping_cb *cb) buf.addr = cb->send_dma_addr; buf.size = sizeof cb->send_buf; - DEBUG_LOG(cb, "send buf dma_addr %llx size %d\n", buf.addr, - (int)buf.size); + DEBUG_LOG(cb, "send buf dma_addr %jx size %d\n", + (uintmax_t)buf.addr, (int)buf.size); iovbase = cb->send_dma_addr; cb->send_mr = ib_reg_phys_mr(cb->pd, &buf, 1, 0, &iovbase); @@ -657,8 +657,8 @@ static int krping_setup_buffers(struct krping_cb *cb) ret = PTR_ERR(cb->rdma_mr); goto bail; } - DEBUG_LOG(cb, "rdma buf dma_addr %llx size %d mr rkey 0x%x\n", - buf.addr, (int)buf.size, cb->rdma_mr->rkey); + DEBUG_LOG(cb, "rdma buf dma_addr %jx size %d mr rkey 0x%x\n", + (uintmax_t)buf.addr, (int)buf.size, cb->rdma_mr->rkey); break; default: ret = -EINVAL; @@ -691,8 +691,8 @@ static int krping_setup_buffers(struct krping_cb *cb) buf.addr = cb->start_dma_addr; buf.size = cb->size; - DEBUG_LOG(cb, "start buf dma_addr %llx size %d\n", - buf.addr, (int)buf.size); + DEBUG_LOG(cb, "start buf dma_addr %jx size %d\n", + (uintmax_t)buf.addr, (int)buf.size); iovbase = cb->start_dma_addr; cb->start_mr = ib_reg_phys_mr(cb->pd, &buf, 1, flags, @@ -882,16 +882,16 @@ static u32 krping_rdma_rkey(struct krping_cb *cb, u64 buf, int post_inv) for (i=0; i < cb->fastreg_wr.wr.fast_reg.page_list_len; i++, p += PAGE_SIZE) { cb->page_list->page_list[i] = p; - DEBUG_LOG(cb, "page_list[%d] 0x%llx\n", i, p); + DEBUG_LOG(cb, "page_list[%d] 0x%jx\n", i, (uintmax_t)p); } DEBUG_LOG(cb, "post_inv = %d, fastreg new rkey 0x%x shift %u len %u" - " iova_start %llx page_list_len %u\n", + " iova_start %jx page_list_len %u\n", post_inv, cb->fastreg_wr.wr.fast_reg.rkey, cb->fastreg_wr.wr.fast_reg.page_shift, cb->fastreg_wr.wr.fast_reg.length, - cb->fastreg_wr.wr.fast_reg.iova_start, + (uintmax_t)cb->fastreg_wr.wr.fast_reg.iova_start, cb->fastreg_wr.wr.fast_reg.page_list_len); if (post_inv) @@ -930,9 +930,9 @@ static u32 krping_rdma_rkey(struct krping_cb *cb, u64 buf, int post_inv) #else cb->bind_attr.addr = buf; #endif - DEBUG_LOG(cb, "binding mw rkey 0x%x to buf %llx mr rkey 0x%x\n", + DEBUG_LOG(cb, "binding mw rkey 0x%x to buf %jx mr rkey 0x%x\n", #ifdef BIND_INFO - cb->mw->rkey, buf, cb->bind_attr.bind_info.mr->rkey); + cb->mw->rkey, (uintmax_t)buf, cb->bind_attr.bind_info.mr->rkey); #else cb->mw->rkey, buf, cb->bind_attr.mr->rkey); #endif @@ -1199,8 +1199,8 @@ static void rlat_test(struct krping_cb *cb) } PRINTF(cb, "delta sec %lu delta usec %lu iter %d size %d\n", - stop_tv.tv_sec - start_tv.tv_sec, - stop_tv.tv_usec - start_tv.tv_usec, + (unsigned long)(stop_tv.tv_sec - start_tv.tv_sec), + (unsigned long)(stop_tv.tv_usec - start_tv.tv_usec), scnt, cb->size); } @@ -1333,12 +1333,12 @@ static void wlat_test(struct krping_cb *cb) sum_poll += poll_cycles_stop[i] - poll_cycles_start[i]; sum_last_poll += poll_cycles_stop[i]-last_poll_cycles_start[i]; } - PRINTF(cb, + PRINTF(cb, "delta sec %lu delta usec %lu iter %d size %d cycle_iters %d" " sum_post %llu sum_poll %llu sum_last_poll %llu\n", - stop_tv.tv_sec - start_tv.tv_sec, - stop_tv.tv_usec - start_tv.tv_usec, - scnt, cb->size, cycle_iters, + (unsigned long)(stop_tv.tv_sec - start_tv.tv_sec), + (unsigned long)(stop_tv.tv_usec - start_tv.tv_usec), + scnt, cb->size, cycle_iters, (unsigned long long)sum_post, (unsigned long long)sum_poll, (unsigned long long)sum_last_poll); kfree(post_cycles_start); @@ -1459,11 +1459,11 @@ static void bw_test(struct krping_cb *cb) sum_poll += poll_cycles_stop[i] - poll_cycles_start[i]; sum_last_poll += poll_cycles_stop[i]-last_poll_cycles_start[i]; } - PRINTF(cb, + PRINTF(cb, "delta sec %lu delta usec %lu iter %d size %d cycle_iters %d" " sum_post %llu sum_poll %llu sum_last_poll %llu\n", - stop_tv.tv_sec - start_tv.tv_sec, - stop_tv.tv_usec - start_tv.tv_usec, + (unsigned long)(stop_tv.tv_sec - start_tv.tv_sec), + (unsigned long)(stop_tv.tv_usec - start_tv.tv_usec), scnt, cb->size, cycle_iters, (unsigned long long)sum_post, (unsigned long long)sum_poll, (unsigned long long)sum_last_poll); @@ -1588,12 +1588,12 @@ static int fastreg_supported(struct krping_cb *cb, int server) return 0; } if (!(attr.device_cap_flags & IB_DEVICE_MEM_MGT_EXTENSIONS)) { - PRINTF(cb, "Fastreg not supported - device_cap_flags 0x%x\n", - attr.device_cap_flags); + PRINTF(cb, "Fastreg not supported - device_cap_flags 0x%llx\n", + (unsigned long long)attr.device_cap_flags); return 0; } - DEBUG_LOG(cb, "Fastreg supported - device_cap_flags 0x%x\n", - attr.device_cap_flags); + DEBUG_LOG(cb, "Fastreg supported - device_cap_flags 0x%jx\n", + (uintmax_t)attr.device_cap_flags); return 1; } @@ -1664,19 +1664,19 @@ static void krping_fr_test5(struct krping_cb *cb) } pl = kzalloc(sizeof *pl * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s pl %p size %lu\n", __func__, pl, sizeof *pl * depth); + DEBUG_LOG(cb, "%s pl %p size %zu\n", __func__, pl, sizeof *pl * depth); mr = kzalloc(sizeof *mr * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s mr %p size %lu\n", __func__, mr, sizeof *mr * depth); + DEBUG_LOG(cb, "%s mr %p size %zu\n", __func__, mr, sizeof *mr * depth); fr = kzalloc(sizeof *fr * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s fr %p size %lu\n", __func__, fr, sizeof *fr * depth); + DEBUG_LOG(cb, "%s fr %p size %zu\n", __func__, fr, sizeof *fr * depth); sgl = kzalloc(sizeof *sgl * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s sgl %p size %lu\n", __func__, sgl, sizeof *sgl * depth); + DEBUG_LOG(cb, "%s sgl %p size %zu\n", __func__, sgl, sizeof *sgl * depth); read = kzalloc(sizeof *read * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s read %p size %lu\n", __func__, read, sizeof *read * depth); + DEBUG_LOG(cb, "%s read %p size %zu\n", __func__, read, sizeof *read * depth); buf = kzalloc(sizeof *buf * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s buf %p size %lu\n", __func__, buf, sizeof *buf * depth); + DEBUG_LOG(cb, "%s buf %p size %zu\n", __func__, buf, sizeof *buf * depth); dma_addr = kzalloc(sizeof *dma_addr * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s dma_addr %p size %lu\n", __func__, dma_addr, sizeof *dma_addr * depth); + DEBUG_LOG(cb, "%s dma_addr %p size %zu\n", __func__, dma_addr, sizeof *dma_addr * depth); if (!pl || !mr || !fr || !read || !sgl || !buf || !dma_addr) { PRINTF(cb, "kzalloc failed\n"); goto err1; @@ -1719,16 +1719,16 @@ static void krping_fr_test5(struct krping_cb *cb) DEBUG_LOG(cb, "%s dma_addr[%u] %p\n", __func__, scnt, (void *)dma_addr[scnt]); for (i=0; ipage_list[i] = ((unsigned long)dma_addr[scnt] & PAGE_MASK) + (i * PAGE_SIZE); - DEBUG_LOG(cb, "%s pl[%u]->page_list[%u] 0x%llx\n", - __func__, scnt, i, pl[scnt]->page_list[i]); + DEBUG_LOG(cb, "%s pl[%u]->page_list[%u] 0x%jx\n", + __func__, scnt, i, (uintmax_t)pl[scnt]->page_list[i]); } sgl[scnt].lkey = mr[scnt]->rkey; sgl[scnt].length = cb->size; sgl[scnt].addr = (u64)buf[scnt]; - DEBUG_LOG(cb, "%s sgl[%u].lkey 0x%x length %u addr 0x%llx\n", + DEBUG_LOG(cb, "%s sgl[%u].lkey 0x%x length %u addr 0x%jx\n", __func__, scnt, sgl[scnt].lkey, sgl[scnt].length, - sgl[scnt].addr); + (uintmax_t)sgl[scnt].addr); fr[scnt].opcode = IB_WR_FAST_REG_MR; fr[scnt].wr_id = scnt; @@ -1778,9 +1778,9 @@ static void krping_fr_test5(struct krping_cb *cb) if (ret == 1) { if (wc.status) { PRINTF(cb, - "completion error %u wr_id %lld " + "completion error %u wr_id %ju " "opcode %d\n", wc.status, - wc.wr_id, wc.opcode); + (uintmax_t)wc.wr_id, wc.opcode); goto err2; } count++; @@ -1877,8 +1877,8 @@ static void krping_fr_test5_server(struct krping_cb *cb) while (cb->state < RDMA_READ_ADV) { krping_cq_event_handler(cb->cq, cb); } - DEBUG_LOG(cb, "%s client STAG %x TO 0x%llx\n", __func__, - cb->remote_rkey, cb->remote_addr); + DEBUG_LOG(cb, "%s client STAG %x TO 0x%jx\n", __func__, + cb->remote_rkey, (uintmax_t)cb->remote_addr); /* Send STAG/TO/Len to client */ krping_format_send(cb, cb->start_dma_addr); @@ -1940,7 +1940,8 @@ static void krping_fr_test5_client(struct krping_cb *cb) while (cb->state < RDMA_WRITE_ADV) { krping_cq_event_handler(cb->cq, cb); } - DEBUG_LOG(cb, "%s server STAG %x TO 0x%llx\n", __func__, cb->remote_rkey, cb->remote_addr); + DEBUG_LOG(cb, "%s server STAG %x TO 0x%jx\n", __func__, cb->remote_rkey, + (uintmax_t)cb->remote_addr); return krping_fr_test5(cb); } @@ -1978,28 +1979,28 @@ static void krping_fr_test6(struct krping_cb *cb) } pl = kzalloc(sizeof *pl * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s pl %p size %lu\n", __func__, pl, sizeof *pl * depth); + DEBUG_LOG(cb, "%s pl %p size %zu\n", __func__, pl, sizeof *pl * depth); mr = kzalloc(sizeof *mr * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s mr %p size %lu\n", __func__, mr, sizeof *mr * depth); + DEBUG_LOG(cb, "%s mr %p size %zu\n", __func__, mr, sizeof *mr * depth); fr = kzalloc(sizeof *fr * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s fr %p size %lu\n", __func__, fr, sizeof *fr * depth); + DEBUG_LOG(cb, "%s fr %p size %zu\n", __func__, fr, sizeof *fr * depth); sgl = kzalloc(sizeof *sgl * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s sgl %p size %lu\n", __func__, sgl, sizeof *sgl * depth); + DEBUG_LOG(cb, "%s sgl %p size %zu\n", __func__, sgl, sizeof *sgl * depth); write = kzalloc(sizeof *write * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s read %p size %lu\n", __func__, write, sizeof *write * depth); + DEBUG_LOG(cb, "%s read %p size %zu\n", __func__, write, sizeof *write * depth); inv = kzalloc(sizeof *inv * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s inv %p size %lu\n", __func__, inv, sizeof *inv * depth); + DEBUG_LOG(cb, "%s inv %p size %zu\n", __func__, inv, sizeof *inv * depth); buf = kzalloc(sizeof *buf * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s buf %p size %lu\n", __func__, buf, sizeof *buf * depth); + DEBUG_LOG(cb, "%s buf %p size %zu\n", __func__, buf, sizeof *buf * depth); dma_addr = kzalloc(sizeof *dma_addr * depth, GFP_KERNEL); - DEBUG_LOG(cb, "%s dma_addr %p size %lu\n", __func__, dma_addr, sizeof *dma_addr * depth); + DEBUG_LOG(cb, "%s dma_addr %p size %zu\n", __func__, dma_addr, sizeof *dma_addr * depth); if (!pl || !mr || !fr || !write || !sgl || !buf || !dma_addr) { PRINTF(cb, "kzalloc failed\n"); @@ -2043,8 +2044,8 @@ static void krping_fr_test6(struct krping_cb *cb) DEBUG_LOG(cb, "%s dma_addr[%u] %p\n", __func__, scnt, (void *)dma_addr[scnt]); for (i=0; ipage_list[i] = ((unsigned long)dma_addr[scnt] & PAGE_MASK) + (i * PAGE_SIZE); - DEBUG_LOG(cb, "%s pl[%u]->page_list[%u] 0x%llx\n", - __func__, scnt, i, pl[scnt]->page_list[i]); + DEBUG_LOG(cb, "%s pl[%u]->page_list[%u] 0x%jx\n", + __func__, scnt, i, (uintmax_t)pl[scnt]->page_list[i]); } write[scnt].opcode = IB_WR_RDMA_WRITE; @@ -2101,9 +2102,9 @@ static void krping_fr_test6(struct krping_cb *cb) if (ret == 1) { if (wc.status) { PRINTF(cb, - "completion error %u wr_id %lld " + "completion error %u wr_id %ju " "opcode %d\n", wc.status, - wc.wr_id, wc.opcode); + (uintmax_t)wc.wr_id, wc.opcode); goto err2; } count++; @@ -2200,8 +2201,8 @@ static void krping_fr_test6_server(struct krping_cb *cb) while (cb->state < RDMA_READ_ADV) { krping_cq_event_handler(cb->cq, cb); } - DEBUG_LOG(cb, "%s client STAG %x TO 0x%llx\n", __func__, - cb->remote_rkey, cb->remote_addr); + DEBUG_LOG(cb, "%s client STAG %x TO 0x%jx\n", __func__, + cb->remote_rkey, (uintmax_t)cb->remote_addr); /* Send STAG/TO/Len to client */ krping_format_send(cb, cb->start_dma_addr); @@ -2263,7 +2264,8 @@ static void krping_fr_test6_client(struct krping_cb *cb) while (cb->state < RDMA_WRITE_ADV) { krping_cq_event_handler(cb->cq, cb); } - DEBUG_LOG(cb, "%s server STAG %x TO 0x%llx\n", __func__, cb->remote_rkey, cb->remote_addr); + DEBUG_LOG(cb, "%s server STAG %x TO 0x%jx\n", __func__, cb->remote_rkey, + (uintmax_t)cb->remote_addr); return krping_fr_test6(cb); } diff --git a/sys/contrib/rdma/krping/krping.h b/sys/contrib/rdma/krping/krping.h index 04be5311ced0..f201d10475f2 100644 --- a/sys/contrib/rdma/krping/krping.h +++ b/sys/contrib/rdma/krping/krping.h @@ -17,5 +17,4 @@ struct krping_stats { int krping_doit(char *, void *); void krping_walk_cb_list(void (*)(struct krping_stats *, void *), void *); void krping_init(void); -void krping_printf(void *, const char *, ...); int krping_sigpending(void); diff --git a/sys/contrib/rdma/krping/krping_dev.c b/sys/contrib/rdma/krping/krping_dev.c index 2244d72486e0..7902ebfa8f4d 100644 --- a/sys/contrib/rdma/krping/krping_dev.c +++ b/sys/contrib/rdma/krping/krping_dev.c @@ -209,16 +209,6 @@ krping_write(struct cdev *dev, struct uio *uio, int ioflag) return(err); } -void -krping_printf(void *cookie, const char *fmt, ...) -{ - va_list ap; - - va_start(ap, fmt); - vtprintf(cookie, -1, fmt, ap); - va_end(ap); -} - int krping_sigpending(void) { From 7cbd0a2953a27e74f8b1b261808068719c1f5260 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 01:17:03 +0000 Subject: [PATCH 014/143] Simplify building libpam and fix libpam.a not containing the modules since r284345. The change in r284345 moved the creation of openpam_static_modules.o to lib/libpam/static_modules but never managed to get them into libpam.a. Move this logic to lib/libpam/static_libpam and have it create a static library for libpam.a The main lib/libpam/libpam will only create a shared library. No redundancy in compilation or installation exists in this solution. This avoids requiring a pass with -D_NO_LIBPAM_SO_YET. Sponsored by: EMC / Isilon Storage Division --- Makefile.inc1 | 17 +++------------- lib/libpam/Makefile | 9 ++++++--- lib/libpam/libpam/Makefile | 14 ++++++++----- lib/libpam/modules/Makefile.inc | 7 ------- .../Makefile | 20 +++++++++---------- .../Makefile.depend | 0 targets/pseudo/userland/lib/Makefile.depend | 1 + 7 files changed, 28 insertions(+), 40 deletions(-) rename lib/libpam/{static_modules => static_libpam}/Makefile (92%) rename lib/libpam/{static_modules => static_libpam}/Makefile.depend (100%) diff --git a/Makefile.inc1 b/Makefile.inc1 index 648475b98618..27c8808e4499 100644 --- a/Makefile.inc1 +++ b/Makefile.inc1 @@ -1719,7 +1719,7 @@ _prebuild_libs= ${_kerberos5_lib_libasn1} \ lib/libkiconv lib/libkvm lib/liblzma lib/libmd lib/libnv \ ${_lib_casper} \ lib/ncurses/ncurses lib/ncurses/ncursesw \ - lib/libopie lib/libpam ${_lib_libthr} \ + lib/libopie lib/libpam/libpam ${_lib_libthr} \ ${_lib_libradius} lib/libsbuf lib/libtacplus \ lib/libgeom \ ${_cddl_lib_libumem} ${_cddl_lib_libnvpair} \ @@ -1731,6 +1731,7 @@ _prebuild_libs= ${_kerberos5_lib_libasn1} \ ${_secure_lib_libcrypto} ${_lib_libldns} \ ${_secure_lib_libssh} ${_secure_lib_libssl} \ gnu/lib/libdialog + .if ${MK_GNUCXX} != "no" _prebuild_libs+= gnu/lib/libstdc++ gnu/lib/libsupc++ gnu/lib/libstdc++__L: lib/msun__L @@ -1898,7 +1899,7 @@ ${_lib}__PL: .PHONY .MAKE .endif .endfor -.for _lib in ${_startup_libs} ${_prebuild_libs:Nlib/libpam} ${_generic_libs} +.for _lib in ${_startup_libs} ${_prebuild_libs} ${_generic_libs} ${_lib}__L: .PHONY .MAKE .if exists(${.CURDIR}/${_lib}) ${_+_}@${ECHODIR} "===> ${_lib} (obj,all,install)"; \ @@ -1909,18 +1910,6 @@ ${_lib}__L: .PHONY .MAKE .endif .endfor -# libpam is special: we need to build static PAM modules before -# static PAM library, and dynamic PAM library before dynamic PAM -# modules. -lib/libpam__L: .PHONY .MAKE - ${_+_}@${ECHODIR} "===> lib/libpam (obj,all,install)"; \ - cd ${.CURDIR}/lib/libpam; \ - ${MAKE} MK_TESTS=no DIRPRFX=lib/libpam/ obj; \ - ${MAKE} MK_TESTS=no DIRPRFX=lib/libpam/ \ - -D_NO_LIBPAM_SO_YET all; \ - ${MAKE} MK_TESTS=no DIRPRFX=lib/libpam/ \ - -D_NO_LIBPAM_SO_YET install - _prereq_libs: ${_prereq_libs:S/$/__PL/} _startup_libs: ${_startup_libs:S/$/__L/} _prebuild_libs: ${_prebuild_libs:S/$/__L/} diff --git a/lib/libpam/Makefile b/lib/libpam/Makefile index 5c3a2ae60cc5..fa73b95b140d 100644 --- a/lib/libpam/Makefile +++ b/lib/libpam/Makefile @@ -24,8 +24,11 @@ # # $FreeBSD$ -# The modules must be built first, because they are built into the -# static version of libpam. -SUBDIR+= modules libpam static_modules +# The modules link in libpam. They build the static modules as well. +SUBDIR+= libpam modules +SUBDIR_DEPEND_modules= libpam +SUBDIR+= static_libpam +SUBDIR_DEPEND_static_libpam= modules +SUBDIR_PARALLEL= .include diff --git a/lib/libpam/libpam/Makefile b/lib/libpam/libpam/Makefile index 1dc977f610d3..f428a7fc26cf 100644 --- a/lib/libpam/libpam/Makefile +++ b/lib/libpam/libpam/Makefile @@ -38,7 +38,11 @@ OPENPAM= ${.CURDIR}/../../../contrib/openpam .PATH: ${OPENPAM}/include ${OPENPAM}/lib/libpam ${OPENPAM}/doc/man -LIB= pam +# static_libpam will build libpam.a +.if !defined(LIB) +SHLIB= pam +.endif + MK_PROFILE=no SRCS= openpam_asprintf.c \ @@ -98,7 +102,7 @@ SRCS= openpam_asprintf.c \ # Local additions SRCS+= pam_debug_log.c -MAN= openpam.3 \ +MAN?= openpam.3 \ openpam_borrow_cred.3 \ openpam_free_data.3 \ openpam_free_envlist.3 \ @@ -150,10 +154,10 @@ MAN= openpam.3 \ pam_vprompt.3 \ pam.conf.5 -MLINKS= pam.conf.5 pam.d.5 +MLINKS?= pam.conf.5 pam.d.5 CSTD?= c99 -CFLAGS+= -I${.CURDIR} -I${OPENPAM}/include +CFLAGS+= -I${OPENPAM}/include CFLAGS+= -DLIB_MAJ=${SHLIB_MAJOR} CFLAGS+= -DHAVE_DLFUNC=1 CFLAGS+= -DHAVE_FDLOPEN=1 @@ -172,7 +176,7 @@ HEADERS= security/openpam.h \ ADD_HEADERS= security/pam_mod_misc.h # Headers -INCS= ${HEADERS} ${ADD_HEADERS} +INCS?= ${HEADERS} ${ADD_HEADERS} INCSDIR= ${INCLUDEDIR}/security .include diff --git a/lib/libpam/modules/Makefile.inc b/lib/libpam/modules/Makefile.inc index 2da5a7b524ad..899c3cbbc8f6 100644 --- a/lib/libpam/modules/Makefile.inc +++ b/lib/libpam/modules/Makefile.inc @@ -7,14 +7,7 @@ MK_PROFILE= no CFLAGS+= -I${PAMDIR}/include -I${.CURDIR}/../../libpam -# This is nasty. -# For the static case, libpam.a depends on the modules. -# For the dynamic case, the modules depend on libpam.so.N -.if defined(_NO_LIBPAM_SO_YET) -NO_PIC= -.else SHLIB_NAME?= ${LIB}.so.${SHLIB_MAJOR} LIBADD+= pam -.endif .include "../Makefile.inc" diff --git a/lib/libpam/static_modules/Makefile b/lib/libpam/static_libpam/Makefile similarity index 92% rename from lib/libpam/static_modules/Makefile rename to lib/libpam/static_libpam/Makefile index 429e6601e620..f7180e93ef05 100644 --- a/lib/libpam/static_modules/Makefile +++ b/lib/libpam/static_libpam/Makefile @@ -35,15 +35,17 @@ # # $FreeBSD$ -OPENPAM= ${.CURDIR:H:H:H}/contrib/openpam -.PATH: ${OPENPAM}/lib -.PATH: ${OPENPAM}/lib/libpam +.PATH: ${.CURDIR}/../libpam -all: - -SRCS = openpam_static.c +# Only build the static library. +LIB= pam +NO_PIC= +# Avoid redundancy with the master Makefile. MAN= +INCS= +MLINKS= +MK_TESTS= no # # Static modules @@ -61,11 +63,7 @@ STATICOBJS+= openpam_static_modules.o CLEANFILES+= openpam_static.o \ openpam_static_modules.o -.include - -.if empty(_SKIP_BUILD) openpam_static_modules.o: openpam_static.o ${STATIC_MODULES} ${LD} -o ${.TARGET} -r --whole-archive ${.ALLSRC} -all: ${STATICOBJS} -.endif +.include "${.CURDIR}/../libpam/Makefile" diff --git a/lib/libpam/static_modules/Makefile.depend b/lib/libpam/static_libpam/Makefile.depend similarity index 100% rename from lib/libpam/static_modules/Makefile.depend rename to lib/libpam/static_libpam/Makefile.depend diff --git a/targets/pseudo/userland/lib/Makefile.depend b/targets/pseudo/userland/lib/Makefile.depend index 7b911fea9393..dac80744e227 100644 --- a/targets/pseudo/userland/lib/Makefile.depend +++ b/targets/pseudo/userland/lib/Makefile.depend @@ -117,6 +117,7 @@ DIRDEPS = \ lib/libpam/modules/pam_ssh \ lib/libpam/modules/pam_tacplus \ lib/libpam/modules/pam_unix \ + lib/libpam/static_libpam \ lib/libpcap \ lib/libpe \ lib/libpjdlog \ From 96a3b885102b26abf4d73cc48191ff4773dcf323 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 01:17:37 +0000 Subject: [PATCH 015/143] Build libpam modules in parallel. MFC after: 2 weeks Sponsored by: EMC / Isilon Storage Division --- lib/libpam/modules/Makefile | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/libpam/modules/Makefile b/lib/libpam/modules/Makefile index cacf0115da7a..ee1359bd3acc 100644 --- a/lib/libpam/modules/Makefile +++ b/lib/libpam/modules/Makefile @@ -27,5 +27,6 @@ .include "modules.inc" SUBDIR= ${MODULES} +SUBDIR_PARALLEL= .include From f79bedf5addb766f0b1fedbfadbbbc7345756a53 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 01:20:00 +0000 Subject: [PATCH 016/143] Regenerate --- share/man/man5/src.conf.5 | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/share/man/man5/src.conf.5 b/share/man/man5/src.conf.5 index e6388033a5f2..0d30a168688d 100644 --- a/share/man/man5/src.conf.5 +++ b/share/man/man5/src.conf.5 @@ -1,7 +1,7 @@ .\" DO NOT EDIT-- this file is automatically generated. .\" from FreeBSD: head/tools/build/options/makeman 292283 2015-12-15 18:42:30Z bdrewery .\" $FreeBSD$ -.Dd April 11, 2016 +.Dd April 13, 2016 .Dt SRC.CONF 5 .Os .Sh NAME @@ -821,11 +821,14 @@ Set to not build .\" from FreeBSD: head/tools/build/options/WITHOUT_INET_SUPPORT 221266 2011-04-30 17:58:28Z bz Set to build libraries, programs, and kernel modules without IPv4 support. .It Va WITHOUT_INSTALLLIB -.\" from FreeBSD: head/tools/build/options/WITHOUT_INSTALLLIB 174497 2007-12-09 21:56:21Z dougb +.\" from FreeBSD: head/tools/build/options/WITHOUT_INSTALLLIB 297941 2016-04-13 21:01:58Z bdrewery Set this if you do not want to install optional libraries. For example when creating a .Xr nanobsd 8 image. +.Bf -symbolic +The option does not work for build targets. +.Ef .It Va WITH_INSTALL_AS_USER .\" from FreeBSD: head/tools/build/options/WITH_INSTALL_AS_USER 238021 2012-07-02 20:24:01Z marcel Set to make install targets succeed for non-root users by installing @@ -1435,13 +1438,10 @@ and Set to not build or install .Xr timed 8 . .It Va WITHOUT_TOOLCHAIN -.\" from FreeBSD: head/tools/build/options/WITHOUT_TOOLCHAIN 273172 2014-10-16 15:55:13Z brooks +.\" from FreeBSD: head/tools/build/options/WITHOUT_TOOLCHAIN 297939 2016-04-13 20:55:05Z bdrewery Set to not install header or programs used for program development, compilers, debuggers etc. -.Bf -symbolic -The option does not work for build targets. -.Ef When set, it also enforces the following options: .Pp .Bl -item -compact From d303752b5067164c3abf580a6c4ea8d0dfdf7a67 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Thu, 14 Apr 2016 04:16:31 +0000 Subject: [PATCH 017/143] Add comment about where b_iocmd and b_ioflags come from. --- sys/sys/buf.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sys/sys/buf.h b/sys/sys/buf.h index c85b88ff54f4..012493ca84dc 100644 --- a/sys/sys/buf.h +++ b/sys/sys/buf.h @@ -98,8 +98,8 @@ struct buf { void *b_caller1; caddr_t b_data; int b_error; - uint8_t b_iocmd; - uint8_t b_ioflags; + uint8_t b_iocmd; /* BIO_* bio_cmd from bio.h */ + uint8_t b_ioflags; /* BIO_* bio_flags from bio.h */ off_t b_iooffset; long b_resid; void (*b_iodone)(struct buf *); From 47754aa24056aba4a2242c53b2aaf4225f190740 Mon Sep 17 00:00:00 2001 From: Enji Cooper Date: Thu, 14 Apr 2016 04:40:31 +0000 Subject: [PATCH 018/143] Disable fmaxmin_test when compiling it with clang 3.8.0 The testcase always fails today due to how C11 7.6.1/2 is interpreted with clang 3.8.0 when combined with "#pragma STDC FENV_ACCESS ON". This testcase passes with clang <3.8.0 and gcc, so continue testing it with those compiler combinations More intelligent discussion on the issue is in the PR MFC after: never PR: 208703 Sponsored by: EMC / Isilon Storage Division --- lib/msun/tests/Makefile | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/msun/tests/Makefile b/lib/msun/tests/Makefile index b18c07d5a115..5dc280bc6651 100644 --- a/lib/msun/tests/Makefile +++ b/lib/msun/tests/Makefile @@ -1,5 +1,7 @@ # $FreeBSD$ +.include + TESTSRC= ${SRCTOP}/contrib/netbsd-tests/lib/libm # All architectures on FreeBSD have fenv.h @@ -47,7 +49,10 @@ TAP_TESTS_C+= ctrig_test TAP_TESTS_C+= exponential_test TAP_TESTS_C+= fenv_test TAP_TESTS_C+= fma_test +# clang 3.8.0 fails always fails this test. See: bug 208703 +.if ! (${COMPILER_TYPE} == "clang" && ${COMPILER_VERSION} == 30800) TAP_TESTS_C+= fmaxmin_test +.endif TAP_TESTS_C+= ilogb_test TAP_TESTS_C+= invtrig_test TAP_TESTS_C+= invctrig_test From bd3bce41db1e29fb96124a57e89d02e56c4c242b Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Thu, 14 Apr 2016 04:59:51 +0000 Subject: [PATCH 019/143] Deprecate using hints.acpi.0.rsdp to communicate the RSDP to the system. This uses the hints mechnanism. This mostly works today because when there's no static hints (the default), this value can be fetched from the hint. When there is a static hints file, the hint passed from the boot loader to the kernel is ignored, but for the BIOS case we're able to find it anyway. However, with UEFI, the fallback doesn't work, so we get a panic instead. Switch to acpi.rsdp and use TUNABLE_ULONG_FETCH instead. Continue to generate the old values to allow for transitions. In addition, fall back to the old method if the new method isn't present. Add comments about all this. Differential Revision: https://reviews.freebsd.org/D5866 --- sys/boot/efi/loader/arch/amd64/elf64_freebsd.c | 17 +++++++++++++++++ sys/boot/i386/libi386/biosacpi.c | 17 ++++++++++++++++- sys/x86/acpica/OsdEnvironment.c | 11 +++++++++++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/sys/boot/efi/loader/arch/amd64/elf64_freebsd.c b/sys/boot/efi/loader/arch/amd64/elf64_freebsd.c index 1b95cdede4b5..a1096d9a650b 100644 --- a/sys/boot/efi/loader/arch/amd64/elf64_freebsd.c +++ b/sys/boot/efi/loader/arch/amd64/elf64_freebsd.c @@ -101,6 +101,17 @@ elf64_exec(struct preloaded_file *fp) char buf[24]; int revision; + /* + * Report the RSDP to the kernel. While this can be found with + * a BIOS boot, the RSDP may be elsewhere when booted from UEFI. + * The old code used the 'hints' method to communite this to + * the kernel. However, while convenient, the 'hints' method + * is fragile and does not work when static hints are compiled + * into the kernel. Instead, move to setting different tunables + * that start with acpi. The old 'hints' can be removed before + * we branch for FreeBSD 12. + */ + rsdp = efi_get_table(&acpi20_guid); if (rsdp == NULL) { rsdp = efi_get_table(&acpi_guid); @@ -108,23 +119,29 @@ elf64_exec(struct preloaded_file *fp) if (rsdp != NULL) { sprintf(buf, "0x%016llx", (unsigned long long)rsdp); setenv("hint.acpi.0.rsdp", buf, 1); + setenv("acpi.rsdp", buf, 1); revision = rsdp->Revision; if (revision == 0) revision = 1; sprintf(buf, "%d", revision); setenv("hint.acpi.0.revision", buf, 1); + setenv("acpi.revision", buf, 1); strncpy(buf, rsdp->OemId, sizeof(rsdp->OemId)); buf[sizeof(rsdp->OemId)] = '\0'; setenv("hint.acpi.0.oem", buf, 1); + setenv("acpi.oem", buf, 1); sprintf(buf, "0x%016x", rsdp->RsdtPhysicalAddress); setenv("hint.acpi.0.rsdt", buf, 1); + setenv("acpi.rsdt", buf, 1); if (revision >= 2) { /* XXX extended checksum? */ sprintf(buf, "0x%016llx", (unsigned long long)rsdp->XsdtPhysicalAddress); setenv("hint.acpi.0.xsdt", buf, 1); + setenv("acpi.xsdt", buf, 1); sprintf(buf, "%d", rsdp->Length); setenv("hint.acpi.0.xsdt_length", buf, 1); + setenv("acpi.xsdt_length", buf, 1); } } diff --git a/sys/boot/i386/libi386/biosacpi.c b/sys/boot/i386/libi386/biosacpi.c index bedc722e850d..8167fca7b622 100644 --- a/sys/boot/i386/libi386/biosacpi.c +++ b/sys/boot/i386/libi386/biosacpi.c @@ -60,25 +60,40 @@ biosacpi_detect(void) if ((rsdp = biosacpi_find_rsdp()) == NULL) return; - /* export values from the RSDP */ + /* + * Report the RSDP to the kernel. While this can be found with + * a BIOS boot, the RSDP may be elsewhere when booted from UEFI. + * The old code used the 'hints' method to communite this to + * the kernel. However, while convenient, the 'hints' method + * is fragile and does not work when static hints are compiled + * into the kernel. Instead, move to setting different tunables + * that start with acpi. The old 'hints' can be removed before + * we branch for FreeBSD 12. + */ sprintf(buf, "0x%08x", VTOP(rsdp)); setenv("hint.acpi.0.rsdp", buf, 1); + setenv("acpi.rsdp", buf, 1); revision = rsdp->Revision; if (revision == 0) revision = 1; sprintf(buf, "%d", revision); setenv("hint.acpi.0.revision", buf, 1); + setenv("acpi.revision", buf, 1); strncpy(buf, rsdp->OemId, sizeof(rsdp->OemId)); buf[sizeof(rsdp->OemId)] = '\0'; setenv("hint.acpi.0.oem", buf, 1); + setenv("acpi.oem", buf, 1); sprintf(buf, "0x%08x", rsdp->RsdtPhysicalAddress); setenv("hint.acpi.0.rsdt", buf, 1); + setenv("acpi.rsdt", buf, 1); if (revision >= 2) { /* XXX extended checksum? */ sprintf(buf, "0x%016llx", rsdp->XsdtPhysicalAddress); setenv("hint.acpi.0.xsdt", buf, 1); + setenv("acpi.xsdt", buf, 1); sprintf(buf, "%d", rsdp->Length); setenv("hint.acpi.0.xsdt_length", buf, 1); + setenv("acpi.xsdt_length", buf, 1); } } diff --git a/sys/x86/acpica/OsdEnvironment.c b/sys/x86/acpica/OsdEnvironment.c index be612b5335aa..ab8a7fbaacc0 100644 --- a/sys/x86/acpica/OsdEnvironment.c +++ b/sys/x86/acpica/OsdEnvironment.c @@ -30,6 +30,7 @@ __FBSDID("$FreeBSD$"); #include #include +#include #include #include @@ -59,6 +60,16 @@ acpi_get_root_from_loader(void) { long acpi_root; + if (TUNABLE_ULONG_FETCH("acpi.rsdp", &acpi_root)) + return (acpi_root); + + /* + * The hints mechanism is unreliable (it fails if anybody ever + * compiled in hints to the kernel). It has been replaced + * by the tunable method, but is used here as a fallback to + * retain maximum compatibility between old loaders and new + * kernels. It can be removed after 11.0R. + */ if (resource_long_value("acpi", 0, "rsdp", &acpi_root) == 0) return (acpi_root); From 9a8fa125c1254266563fb16e3c94e4c677906121 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Thu, 14 Apr 2016 05:10:41 +0000 Subject: [PATCH 020/143] Bump bio_cmd and bio_*flags from 8 bits to 16. Differential Revision: https://reviews.freebsd.org/D5784 --- sys/geom/geom_io.c | 4 ++-- sys/geom/geom_subr.c | 4 ++-- sys/geom/mirror/g_mirror.c | 2 +- sys/geom/raid3/g_raid3.c | 2 +- sys/sys/bio.h | 8 ++++---- sys/sys/buf.h | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/sys/geom/geom_io.c b/sys/geom/geom_io.c index 61f70c1c27fd..8270274cac33 100644 --- a/sys/geom/geom_io.c +++ b/sys/geom/geom_io.c @@ -504,11 +504,11 @@ g_io_request(struct bio *bp, struct g_consumer *cp) cmd = bp->bio_cmd; if (cmd == BIO_READ || cmd == BIO_WRITE || cmd == BIO_GETATTR) { KASSERT(bp->bio_data != NULL, - ("NULL bp->data in g_io_request(cmd=%hhu)", bp->bio_cmd)); + ("NULL bp->data in g_io_request(cmd=%hu)", bp->bio_cmd)); } if (cmd == BIO_DELETE || cmd == BIO_FLUSH) { KASSERT(bp->bio_data == NULL, - ("non-NULL bp->data in g_io_request(cmd=%hhu)", + ("non-NULL bp->data in g_io_request(cmd=%hu)", bp->bio_cmd)); } if (cmd == BIO_READ || cmd == BIO_WRITE || cmd == BIO_DELETE) { diff --git a/sys/geom/geom_subr.c b/sys/geom/geom_subr.c index bf14a86e8ee7..54a99bfe4560 100644 --- a/sys/geom/geom_subr.c +++ b/sys/geom/geom_subr.c @@ -1508,8 +1508,8 @@ DB_SHOW_COMMAND(bio, db_show_bio) db_printf("BIO %p\n", bp); db_print_bio_cmd(bp); db_print_bio_flags(bp); - db_printf(" cflags: 0x%hhx\n", bp->bio_cflags); - db_printf(" pflags: 0x%hhx\n", bp->bio_pflags); + db_printf(" cflags: 0x%hx\n", bp->bio_cflags); + db_printf(" pflags: 0x%hx\n", bp->bio_pflags); db_printf(" offset: %jd\n", (intmax_t)bp->bio_offset); db_printf(" length: %jd\n", (intmax_t)bp->bio_length); db_printf(" bcount: %ld\n", bp->bio_bcount); diff --git a/sys/geom/mirror/g_mirror.c b/sys/geom/mirror/g_mirror.c index 70f5eb115fe3..59da98027266 100644 --- a/sys/geom/mirror/g_mirror.c +++ b/sys/geom/mirror/g_mirror.c @@ -1905,7 +1905,7 @@ g_mirror_worker(void *arg) g_mirror_sync_request(bp); /* WRITE */ else { KASSERT(0, - ("Invalid request cflags=0x%hhx to=%s.", + ("Invalid request cflags=0x%hx to=%s.", bp->bio_cflags, bp->bio_to->name)); } } else { diff --git a/sys/geom/raid3/g_raid3.c b/sys/geom/raid3/g_raid3.c index 584076f4536d..617f72e21bc2 100644 --- a/sys/geom/raid3/g_raid3.c +++ b/sys/geom/raid3/g_raid3.c @@ -2127,7 +2127,7 @@ g_raid3_worker(void *arg) g_raid3_sync_request(bp); /* WRITE */ else { KASSERT(0, - ("Invalid request cflags=0x%hhx to=%s.", + ("Invalid request cflags=0x%hx to=%s.", bp->bio_cflags, bp->bio_to->name)); } } else if (g_raid3_register_request(bp) != 0) { diff --git a/sys/sys/bio.h b/sys/sys/bio.h index 8b3a5fcb6a37..37fefbfc37bd 100644 --- a/sys/sys/bio.h +++ b/sys/sys/bio.h @@ -77,10 +77,10 @@ typedef void bio_task_t(void *); * The bio structure describes an I/O operation in the kernel. */ struct bio { - uint8_t bio_cmd; /* I/O operation. */ - uint8_t bio_flags; /* General flags. */ - uint8_t bio_cflags; /* Private use by the consumer. */ - uint8_t bio_pflags; /* Private use by the provider. */ + uint16_t bio_cmd; /* I/O operation. */ + uint16_t bio_flags; /* General flags. */ + uint16_t bio_cflags; /* Private use by the consumer. */ + uint16_t bio_pflags; /* Private use by the provider. */ struct cdev *bio_dev; /* Device to do I/O on. */ struct disk *bio_disk; /* Valid below geom_disk.c only */ off_t bio_offset; /* Offset into file. */ diff --git a/sys/sys/buf.h b/sys/sys/buf.h index 012493ca84dc..4255afdf6bcf 100644 --- a/sys/sys/buf.h +++ b/sys/sys/buf.h @@ -98,8 +98,8 @@ struct buf { void *b_caller1; caddr_t b_data; int b_error; - uint8_t b_iocmd; /* BIO_* bio_cmd from bio.h */ - uint8_t b_ioflags; /* BIO_* bio_flags from bio.h */ + uint16_t b_iocmd; /* BIO_* bio_cmd from bio.h */ + uint16_t b_ioflags; /* BIO_* bio_flags from bio.h */ off_t b_iooffset; long b_resid; void (*b_iodone)(struct buf *); From f8a39033c26ff76570ec22b1e1afa739eed9b5dc Mon Sep 17 00:00:00 2001 From: Andrew Turner Date: Thu, 14 Apr 2016 10:43:28 +0000 Subject: [PATCH 021/143] Set the upper limit of the DMAP region to the limit of RAM as was found in the physmap. This will reduce the likelihood of an issue where we have device memory mapped in the DMAP. This can only happen if it is within the same 1G block of normal memory. Reviewed by: kib Obtained from: ABT Systems Ltd Sponsored by: The FreeBSD Foundation Differential Revision: https://reviews.freebsd.org/D5938 --- sys/arm64/arm64/pmap.c | 21 ++++++++++++++------- sys/arm64/include/vmparam.h | 8 +++++--- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/sys/arm64/arm64/pmap.c b/sys/arm64/arm64/pmap.c index f8a7fddb74a5..2cf3c3325c40 100644 --- a/sys/arm64/arm64/pmap.c +++ b/sys/arm64/arm64/pmap.c @@ -221,6 +221,8 @@ struct msgbuf *msgbufp = NULL; static struct rwlock_padalign pvh_global_lock; vm_paddr_t dmap_phys_base; /* The start of the dmap region */ +vm_paddr_t dmap_phys_max; /* The limit of the dmap region */ +vm_offset_t dmap_max_addr; /* The virtual address limit of the dmap */ /* This code assumes all L1 DMAP entries will be used */ CTASSERT((DMAP_MIN_ADDRESS & ~L0_OFFSET) == DMAP_MIN_ADDRESS); @@ -550,15 +552,15 @@ pmap_early_vtophys(vm_offset_t l1pt, vm_offset_t va) } static void -pmap_bootstrap_dmap(vm_offset_t kern_l1, vm_paddr_t kernstart) +pmap_bootstrap_dmap(vm_offset_t kern_l1, vm_paddr_t min_pa, vm_paddr_t max_pa) { vm_offset_t va; vm_paddr_t pa; u_int l1_slot; - pa = dmap_phys_base = kernstart & ~L1_OFFSET; + pa = dmap_phys_base = min_pa & ~L1_OFFSET; va = DMAP_MIN_ADDRESS; - for (; va < DMAP_MAX_ADDRESS; + for (; va < DMAP_MAX_ADDRESS && pa < max_pa; pa += L1_SIZE, va += L1_SIZE, l1_slot++) { l1_slot = ((va - DMAP_MIN_ADDRESS) >> L1_SHIFT); @@ -567,6 +569,10 @@ pmap_bootstrap_dmap(vm_offset_t kern_l1, vm_paddr_t kernstart) ATTR_IDX(CACHED_MEMORY) | L1_BLOCK); } + /* Set the upper limit of the DMAP region */ + dmap_phys_max = pa; + dmap_max_addr = va; + cpu_dcache_wb_range((vm_offset_t)pagetable_dmap, PAGE_SIZE * DMAP_TABLES); cpu_tlb_flushID(); @@ -651,7 +657,7 @@ pmap_bootstrap(vm_offset_t l0pt, vm_offset_t l1pt, vm_paddr_t kernstart, pt_entry_t *l2; vm_offset_t va, freemempos; vm_offset_t dpcpu, msgbufpv; - vm_paddr_t pa, min_pa; + vm_paddr_t pa, max_pa, min_pa; int i; kern_delta = KERNBASE - kernstart; @@ -671,7 +677,7 @@ pmap_bootstrap(vm_offset_t l0pt, vm_offset_t l1pt, vm_paddr_t kernstart, rw_init(&pvh_global_lock, "pmap pv global"); /* Assume the address we were loaded to is a valid physical address */ - min_pa = KERNBASE - kern_delta; + min_pa = max_pa = KERNBASE - kern_delta; /* * Find the minimum physical address. physmap is sorted, @@ -682,11 +688,12 @@ pmap_bootstrap(vm_offset_t l0pt, vm_offset_t l1pt, vm_paddr_t kernstart, continue; if (physmap[i] <= min_pa) min_pa = physmap[i]; - break; + if (physmap[i + 1] > max_pa) + max_pa = physmap[i + 1]; } /* Create a direct map region early so we can use it for pa -> va */ - pmap_bootstrap_dmap(l1pt, min_pa); + pmap_bootstrap_dmap(l1pt, min_pa, max_pa); va = KERNBASE; pa = KERNBASE - kern_delta; diff --git a/sys/arm64/include/vmparam.h b/sys/arm64/include/vmparam.h index 8dc880924cb0..3d46ece5850d 100644 --- a/sys/arm64/include/vmparam.h +++ b/sys/arm64/include/vmparam.h @@ -162,19 +162,19 @@ #define VM_MIN_KERNEL_ADDRESS (0xffff000000000000UL) #define VM_MAX_KERNEL_ADDRESS (0xffff008000000000UL) -/* 2TiB for the direct map region */ +/* 2 TiB maximum for the direct map region */ #define DMAP_MIN_ADDRESS (0xfffffd0000000000UL) #define DMAP_MAX_ADDRESS (0xffffff0000000000UL) #define DMAP_MIN_PHYSADDR (dmap_phys_base) -#define DMAP_MAX_PHYSADDR (dmap_phys_base + (DMAP_MAX_ADDRESS - DMAP_MIN_ADDRESS)) +#define DMAP_MAX_PHYSADDR (dmap_phys_max) /* True if pa is in the dmap range */ #define PHYS_IN_DMAP(pa) ((pa) >= DMAP_MIN_PHYSADDR && \ (pa) < DMAP_MAX_PHYSADDR) /* True if va is in the dmap range */ #define VIRT_IN_DMAP(va) ((va) >= DMAP_MIN_ADDRESS && \ - (va) < DMAP_MAX_ADDRESS) + (va) < (dmap_max_addr)) #define PHYS_TO_DMAP(pa) \ ({ \ @@ -237,6 +237,8 @@ #ifndef LOCORE extern vm_paddr_t dmap_phys_base; +extern vm_paddr_t dmap_phys_max; +extern vm_offset_t dmap_max_addr; extern u_int tsb_kernel_ldd_phys; extern vm_offset_t vm_max_kernel_address; extern vm_offset_t init_pt_va; From f9e059ac831cfb7b3a312ad0de761b7f2c6cf670 Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Thu, 14 Apr 2016 11:41:30 +0000 Subject: [PATCH 022/143] Use NULL instead of 0 for pointers. fopen(3) returns a FILE pointer, otherwise NULL is returned. MFC after: 2 weeks --- usr.sbin/kgmon/kgmon.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr.sbin/kgmon/kgmon.c b/usr.sbin/kgmon/kgmon.c index 3bc53519b3fc..60c7507e647a 100644 --- a/usr.sbin/kgmon/kgmon.c +++ b/usr.sbin/kgmon/kgmon.c @@ -355,7 +355,7 @@ dumpstate(struct kvmvars *kvp) setprof(kvp, GMON_PROF_OFF); fp = fopen("gmon.out", "w"); - if (fp == 0) { + if (fp == NULL) { warn("gmon.out"); return; } From fa02fc2d8fde6b87d796c30d2200aec5567f4649 Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Thu, 14 Apr 2016 12:25:00 +0000 Subject: [PATCH 023/143] Use NULL instead of 0 for pointers. fopen(3) will return NULL in case it can't open the STREAM. The malloc will return a pointer to the allocated memory if successful, otherwise a NULL pointer is returned. Also add an extra DEBUG1 to print out the error to open a file. Reviewed by: ed Differential Revision: https://svnweb.freebsd.org/changeset/base/297959 --- usr.sbin/rmt/rmt.c | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/usr.sbin/rmt/rmt.c b/usr.sbin/rmt/rmt.c index a5c048faee2f..57c8439a70f5 100644 --- a/usr.sbin/rmt/rmt.c +++ b/usr.sbin/rmt/rmt.c @@ -84,8 +84,10 @@ main(int argc, char **argv) argc--, argv++; if (argc > 0) { debug = fopen(*argv, "w"); - if (debug == 0) + if (debug == NULL) { + DEBUG1("rmtd: error to open %s\n", *argv); exit(1); + } (void)setbuf(debug, (char *)0); } top: @@ -226,10 +228,10 @@ checkbuf(char *rec, int size) if (size <= maxrecsize) return (rec); - if (rec != 0) + if (rec != NULL) free(rec); rec = malloc(size); - if (rec == 0) { + if (rec == NULL) { DEBUG("rmtd: cannot allocate buffer space\n"); exit(4); } From 45be165f23108a8c0c5621c59ec1f23d6f9e8d35 Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Thu, 14 Apr 2016 12:46:46 +0000 Subject: [PATCH 024/143] Use NULL instead of 0 for pointers. The strchr(3) returns a NULL if the character does not appears in the string. The malloc will return NULL if cannot allocate memory. --- usr.sbin/fdread/fdread.c | 2 +- usr.sbin/fdread/fdutil.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/usr.sbin/fdread/fdread.c b/usr.sbin/fdread/fdread.c index 770f92d36cbb..f3c2d9147b9c 100644 --- a/usr.sbin/fdread/fdread.c +++ b/usr.sbin/fdread/fdread.c @@ -170,7 +170,7 @@ doread(int fd, FILE *of, const char *_devname) secsize = 128 << fdt.secsize; tracksize = fdt.sectrac * secsize; mediasize = tracksize * fdt.tracks * fdt.heads; - if ((trackbuf = malloc(tracksize)) == 0) + if ((trackbuf = malloc(tracksize)) == NULL) errx(EX_TEMPFAIL, "out of memory"); if (!quiet) diff --git a/usr.sbin/fdread/fdutil.c b/usr.sbin/fdread/fdutil.c index c66b0c11bc00..bdd295aedf85 100644 --- a/usr.sbin/fdread/fdutil.c +++ b/usr.sbin/fdread/fdutil.c @@ -200,10 +200,10 @@ parse_fmt(const char *s, enum fd_drivetype type, *out = in; for (i = 0;; i++) { - if (s == 0) + if (s == NULL) break; - if ((cp = strchr(s, ',')) == 0) { + if ((cp = strchr(s, ',')) == NULL) { s1 = strdup(s); if (s1 == NULL) abort(); From 4f6dd82a2f6edad76b474ad266640c2867c9db69 Mon Sep 17 00:00:00 2001 From: Alexander Motin Date: Thu, 14 Apr 2016 12:50:27 +0000 Subject: [PATCH 025/143] Remove watchdog timer stop check. There are bunch of reports that this check fails at least on Nuvoton NCT6776 chips. I don't see why this check needed there, and Linux does not have it either. So far this check only made watchdogd unstopable. MFC after: 1 month --- sys/dev/wbwd/wbwd.c | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/sys/dev/wbwd/wbwd.c b/sys/dev/wbwd/wbwd.c index 53e90848def3..75fbea4a5933 100644 --- a/sys/dev/wbwd/wbwd.c +++ b/sys/dev/wbwd/wbwd.c @@ -505,19 +505,10 @@ wb_set_watchdog(struct wb_softc *sc, unsigned int timeout) /* Watchdog is configured as part of LDN 8 (GPIO Port2, Watchdog) */ write_reg(sc, WB_LDN_REG, WB_LDN_REG_LDN8); - /* Disable and validate or arm/reset watchdog. */ if (timeout == 0) { /* Disable watchdog. */ - write_reg(sc, sc->time_reg, 0x00); - sc->reg_timeout = read_reg(sc, sc->time_reg); - (*sc->ext_cfg_exit_f)(sc, 0); - - /* Re-check. */ - if (sc->reg_timeout != 0x00) { - device_printf(sc->dev, "Failed to disable watchdog: " - "0x%02x.\n", sc->reg_timeout); - return (EIO); - } + sc->reg_timeout = 0; + write_reg(sc, sc->time_reg, sc->reg_timeout); } else { /* Read current scaling factor. */ @@ -547,12 +538,12 @@ wb_set_watchdog(struct wb_softc *sc, unsigned int timeout) /* Set timer and arm/reset the watchdog. */ write_reg(sc, sc->time_reg, sc->reg_timeout); - (*sc->ext_cfg_exit_f)(sc, 0); } + (*sc->ext_cfg_exit_f)(sc, 0); + if (sc->debug_verbose) wb_print_state(sc, "After watchdog counter (re)load"); - return (0); } From d11537c7856be0a280f7d76c9e3ed4af3a4a4ed8 Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Thu, 14 Apr 2016 12:51:06 +0000 Subject: [PATCH 026/143] Use NULL instead of 0 for pointers. The malloc will return a pointer to the allocated memory if successful, otherwise a NULL pointer is returned. --- usr.sbin/fstyp/fstyp.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr.sbin/fstyp/fstyp.c b/usr.sbin/fstyp/fstyp.c index cde179f4a391..803a4c8a797a 100644 --- a/usr.sbin/fstyp/fstyp.c +++ b/usr.sbin/fstyp/fstyp.c @@ -82,7 +82,7 @@ read_buf(FILE *fp, off_t off, size_t len) } buf = malloc(len); - if (buf == 0) { + if (buf == NULL) { warn("cannot malloc %zd bytes of memory", len); return (NULL); } From a5de41c600f3cbf587ca87d44e96c8466e46302c Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Thu, 14 Apr 2016 12:53:38 +0000 Subject: [PATCH 027/143] Use NULL instead of 0 for pointers. fopen(3) will return NULL in case it can't open the STREAM. --- usr.sbin/lmcconfig/lmcconfig.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/usr.sbin/lmcconfig/lmcconfig.c b/usr.sbin/lmcconfig/lmcconfig.c index 7fbc2168e1ec..f720e634f8ff 100644 --- a/usr.sbin/lmcconfig/lmcconfig.c +++ b/usr.sbin/lmcconfig/lmcconfig.c @@ -2008,7 +2008,7 @@ load_xilinx(char *name) int c; if (verbose) printf("Load firmware from file %s...\n", name); - if ((f = fopen(name, "r")) == 0) + if ((f = fopen(name, "r")) == NULL) { perror("Failed to open file"); exit(1); From 617e1ff301d5f426b3fea725d9f90cde2b1dc100 Mon Sep 17 00:00:00 2001 From: Hans Petter Selasky Date: Thu, 14 Apr 2016 14:01:28 +0000 Subject: [PATCH 028/143] Add missing port_up checks. When downing a mlxen network adapter we need to check the port_up variable to ensure we don't continue to transmit data or restart timers which can reside in freed memory. Sponsored by: Mellanox Technologies MFC after: 1 week --- sys/ofed/drivers/net/mlx4/en_tx.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/sys/ofed/drivers/net/mlx4/en_tx.c b/sys/ofed/drivers/net/mlx4/en_tx.c index 4358aa631368..463efec9f125 100644 --- a/sys/ofed/drivers/net/mlx4/en_tx.c +++ b/sys/ofed/drivers/net/mlx4/en_tx.c @@ -457,7 +457,7 @@ void mlx4_en_tx_irq(struct mlx4_cq *mcq) struct mlx4_en_priv *priv = netdev_priv(cq->dev); struct mlx4_en_tx_ring *ring = priv->tx_ring[cq->ring]; - if (!spin_trylock(&ring->comp_lock)) + if (priv->port_up == 0 || !spin_trylock(&ring->comp_lock)) return; mlx4_en_process_tx_cq(cq->dev, cq); mod_timer(&cq->timer, jiffies + 1); @@ -473,6 +473,8 @@ void mlx4_en_poll_tx_cq(unsigned long data) INC_PERF_COUNTER(priv->pstats.tx_poll); + if (priv->port_up == 0) + return; if (!spin_trylock(&ring->comp_lock)) { mod_timer(&cq->timer, jiffies + MLX4_EN_TX_POLL_TIMEOUT); return; @@ -494,6 +496,9 @@ static inline void mlx4_en_xmit_poll(struct mlx4_en_priv *priv, int tx_ind) struct mlx4_en_cq *cq = priv->tx_cq[tx_ind]; struct mlx4_en_tx_ring *ring = priv->tx_ring[tx_ind]; + if (priv->port_up == 0) + return; + /* If we don't have a pending timer, set one up to catch our recent post in case the interface becomes idle */ if (!timer_pending(&cq->timer)) @@ -1041,7 +1046,9 @@ mlx4_en_tx_que(void *context, int pending) priv = dev->if_softc; tx_ind = cq->ring; ring = priv->tx_ring[tx_ind]; - if (dev->if_drv_flags & IFF_DRV_RUNNING) { + + if (priv->port_up != 0 && + (dev->if_drv_flags & IFF_DRV_RUNNING) != 0) { mlx4_en_xmit_poll(priv, tx_ind); spin_lock(&ring->tx_lock); if (!drbr_empty(dev, ring->br)) @@ -1058,6 +1065,11 @@ mlx4_en_transmit(struct ifnet *dev, struct mbuf *m) struct mlx4_en_cq *cq; int i, err = 0; + if (priv->port_up == 0) { + m_freem(m); + return (ENETDOWN); + } + /* Compute which queue to use */ if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) { i = (m->m_pkthdr.flowid % 128) % priv->tx_ring_num; @@ -1091,6 +1103,9 @@ mlx4_en_qflush(struct ifnet *dev) struct mlx4_en_tx_ring *ring; struct mbuf *m; + if (priv->port_up == 0) + return; + for (int i = 0; i < priv->tx_ring_num; i++) { ring = priv->tx_ring[i]; spin_lock(&ring->tx_lock); From b03aadaffc87deff373e509486fe8eb6a173ee58 Mon Sep 17 00:00:00 2001 From: Hans Petter Selasky Date: Thu, 14 Apr 2016 14:10:40 +0000 Subject: [PATCH 029/143] Ensure the received IP header gets 32-bits aligned. The FreeBSD's TCP/IP stack assumes that the IP-header is 32-bits aligned when decoding it. Else unaligned 32-bit memory access can happen, which not all processor architectures support. Sponsored by: Mellanox Technologies MFC after: 1 week --- sys/ofed/drivers/net/mlx4/en_rx.c | 15 +++++++++++---- sys/ofed/drivers/net/mlx4/mlx4_en.h | 1 + 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/sys/ofed/drivers/net/mlx4/en_rx.c b/sys/ofed/drivers/net/mlx4/en_rx.c index b29096d56deb..7022d117bacb 100644 --- a/sys/ofed/drivers/net/mlx4/en_rx.c +++ b/sys/ofed/drivers/net/mlx4/en_rx.c @@ -55,7 +55,7 @@ static void mlx4_en_init_rx_desc(struct mlx4_en_priv *priv, int i; /* Set size and memtype fields */ - rx_desc->data[0].byte_count = cpu_to_be32(priv->rx_mb_size); + rx_desc->data[0].byte_count = cpu_to_be32(priv->rx_mb_size - MLX4_NET_IP_ALIGN); rx_desc->data[0].lkey = cpu_to_be32(priv->mdev->mr.key); /* @@ -87,7 +87,10 @@ mlx4_en_alloc_buf(struct mlx4_en_rx_ring *ring, if (unlikely(mb == NULL)) return (-ENOMEM); /* setup correct length */ - mb->m_len = ring->rx_mb_size; + mb->m_pkthdr.len = mb->m_len = ring->rx_mb_size; + + /* make sure IP header gets aligned */ + m_adj(mb, MLX4_NET_IP_ALIGN); /* load spare mbuf into BUSDMA */ err = -bus_dmamap_load_mbuf_sg(ring->dma_tag, ring->spare.dma_map, @@ -117,7 +120,10 @@ mlx4_en_alloc_buf(struct mlx4_en_rx_ring *ring, goto use_spare; /* setup correct length */ - mb->m_len = ring->rx_mb_size; + mb->m_pkthdr.len = mb->m_len = ring->rx_mb_size; + + /* make sure IP header gets aligned */ + m_adj(mb, MLX4_NET_IP_ALIGN); err = -bus_dmamap_load_mbuf_sg(ring->dma_tag, mb_list->dma_map, mb, segs, &nsegs, BUS_DMA_NOWAIT); @@ -249,7 +255,8 @@ static void mlx4_en_free_rx_buf(struct mlx4_en_priv *priv, void mlx4_en_calc_rx_buf(struct net_device *dev) { struct mlx4_en_priv *priv = netdev_priv(dev); - int eff_mtu = dev->if_mtu + ETH_HLEN + VLAN_HLEN + ETH_FCS_LEN; + int eff_mtu = dev->if_mtu + ETH_HLEN + VLAN_HLEN + ETH_FCS_LEN + + MLX4_NET_IP_ALIGN; if (eff_mtu > MJUM16BYTES) { en_err(priv, "MTU(%d) is too big\n", dev->if_mtu); diff --git a/sys/ofed/drivers/net/mlx4/mlx4_en.h b/sys/ofed/drivers/net/mlx4/mlx4_en.h index a584badf4319..c35fd74704ab 100644 --- a/sys/ofed/drivers/net/mlx4/mlx4_en.h +++ b/sys/ofed/drivers/net/mlx4/mlx4_en.h @@ -69,6 +69,7 @@ #define MLX4_EN_PAGE_SHIFT 12 #define MLX4_EN_PAGE_SIZE (1 << MLX4_EN_PAGE_SHIFT) +#define MLX4_NET_IP_ALIGN 2 /* bytes */ #define DEF_RX_RINGS 16 #define MAX_RX_RINGS 128 #define MIN_RX_RINGS 4 From ebcd5b5b31dde9c2120045ca933d0d60b1232f53 Mon Sep 17 00:00:00 2001 From: Hans Petter Selasky Date: Thu, 14 Apr 2016 14:11:32 +0000 Subject: [PATCH 030/143] Remove some unused fields. Sponsored by: Mellanox Technologies MFC after: 1 week --- sys/ofed/drivers/net/mlx4/en_netdev.c | 4 ---- sys/ofed/drivers/net/mlx4/en_rx.c | 3 --- sys/ofed/drivers/net/mlx4/mlx4_en.h | 6 ------ 3 files changed, 13 deletions(-) diff --git a/sys/ofed/drivers/net/mlx4/en_netdev.c b/sys/ofed/drivers/net/mlx4/en_netdev.c index ae7f8576d76e..896b782a9d44 100644 --- a/sys/ofed/drivers/net/mlx4/en_netdev.c +++ b/sys/ofed/drivers/net/mlx4/en_netdev.c @@ -1243,10 +1243,6 @@ int mlx4_en_start_port(struct net_device *dev) /* Calculate Rx buf size */ dev->if_mtu = min(dev->if_mtu, priv->max_mtu); mlx4_en_calc_rx_buf(dev); - priv->rx_alloc_size = max_t(int, 2 * roundup_pow_of_two(priv->rx_mb_size), - PAGE_SIZE); - priv->rx_alloc_order = get_order(priv->rx_alloc_size); - priv->rx_buf_size = roundup_pow_of_two(priv->rx_mb_size); en_dbg(DRV, priv, "Rx buf size:%d\n", priv->rx_mb_size); /* Configure rx cq's and rings */ diff --git a/sys/ofed/drivers/net/mlx4/en_rx.c b/sys/ofed/drivers/net/mlx4/en_rx.c index 7022d117bacb..235a9ab43f12 100644 --- a/sys/ofed/drivers/net/mlx4/en_rx.c +++ b/sys/ofed/drivers/net/mlx4/en_rx.c @@ -391,9 +391,6 @@ int mlx4_en_activate_rx_rings(struct mlx4_en_priv *priv) ring->cons = 0; ring->actual_size = 0; ring->cqn = priv->rx_cq[ring_ind]->mcq.cqn; - ring->rx_alloc_order = priv->rx_alloc_order; - ring->rx_alloc_size = priv->rx_alloc_size; - ring->rx_buf_size = priv->rx_buf_size; ring->rx_mb_size = priv->rx_mb_size; ring->stride = stride; diff --git a/sys/ofed/drivers/net/mlx4/mlx4_en.h b/sys/ofed/drivers/net/mlx4/mlx4_en.h index c35fd74704ab..17afa9e44022 100644 --- a/sys/ofed/drivers/net/mlx4/mlx4_en.h +++ b/sys/ofed/drivers/net/mlx4/mlx4_en.h @@ -316,9 +316,6 @@ struct mlx4_en_rx_ring { u32 cons; u32 buf_size; u8 fcs_del; - u16 rx_alloc_order; - u32 rx_alloc_size; - u32 rx_buf_size; u32 rx_mb_size; int qpn; u8 *buf; @@ -557,9 +554,6 @@ struct mlx4_en_priv { u32 tx_ring_num; u32 rx_ring_num; u32 rx_mb_size; - u16 rx_alloc_order; - u32 rx_alloc_size; - u32 rx_buf_size; struct mlx4_en_tx_ring **tx_ring; struct mlx4_en_rx_ring *rx_ring[MAX_RX_RINGS]; From a48bd011512f66b86f9b06170962575e16555a0c Mon Sep 17 00:00:00 2001 From: Andrew Turner Date: Thu, 14 Apr 2016 14:44:23 +0000 Subject: [PATCH 031/143] Fix the types for the start, end, and count arguments to arm_gic_fdt_alloc_resource. These were the old u_long where they should be rman_res_t. Both of these are the same size on arm64 so this is just for correctness, and would not have led to incorrect behaviour. Obtained from: ABT Systems Ltd Sponsored by: The FreeBSD Foundation --- sys/arm64/arm64/gic_fdt.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/arm64/arm64/gic_fdt.c b/sys/arm64/arm64/gic_fdt.c index 34d8009ad223..f92cd83c0ea6 100644 --- a/sys/arm64/arm64/gic_fdt.c +++ b/sys/arm64/arm64/gic_fdt.c @@ -198,7 +198,7 @@ arm_gic_fdt_attach(device_t dev) static struct resource * arm_gic_fdt_alloc_resource(device_t bus, device_t child, int type, int *rid, - u_long start, u_long end, u_long count, u_int flags) + rman_res_t start, rman_res_t end, rman_res_t count, u_int flags) { struct arm_gic_fdt_softc *sc = device_get_softc(bus); struct gic_devinfo *di; From 5be589603ef88ad50884acd4d9a8daa13584b2fd Mon Sep 17 00:00:00 2001 From: Ruslan Bukin Date: Thu, 14 Apr 2016 15:31:05 +0000 Subject: [PATCH 032/143] Unmagic the thread pointer offset. --- lib/libthr/arch/riscv/include/pthread_md.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/libthr/arch/riscv/include/pthread_md.h b/lib/libthr/arch/riscv/include/pthread_md.h index 86eccc15e0eb..3f5107815de3 100644 --- a/lib/libthr/arch/riscv/include/pthread_md.h +++ b/lib/libthr/arch/riscv/include/pthread_md.h @@ -46,7 +46,7 @@ #define CPU_SPINWAIT #define DTV_OFFSET offsetof(struct tcb, tcb_dtv) -#define TP_OFFSET 0x10 +#define TP_OFFSET sizeof(struct tcb) /* * Variant I tcb. The structure layout is fixed, don't blindly From 820d50e5494ea2761b4daf437bfea60085334a36 Mon Sep 17 00:00:00 2001 From: Andrew Turner Date: Thu, 14 Apr 2016 15:52:11 +0000 Subject: [PATCH 033/143] Sort so pic_if.m is in the correct location with the other kern files. Obtained from: ABT Systems Ltd Sponsored by: The FreeBSD Foundation --- sys/conf/files.arm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/conf/files.arm b/sys/conf/files.arm index a9da11c0cd65..ec1283a2b3d6 100644 --- a/sys/conf/files.arm +++ b/sys/conf/files.arm @@ -57,7 +57,6 @@ arm/arm/mpcore_timer.c optional mpcore_timer arm/arm/nexus.c standard arm/arm/ofw_machdep.c optional fdt arm/arm/physmem.c standard -kern/pic_if.m optional arm_intrng arm/arm/pl190.c optional pl190 arm/arm/pl310.c optional pl310 arm/arm/platform.c optional platform @@ -116,6 +115,7 @@ font.h optional sc \ compile-with "uudecode < /usr/share/syscons/fonts/${SC_DFLT_FONT}-8x16.fnt && file2c 'u_char dflt_font_16[16*256] = {' '};' < ${SC_DFLT_FONT}-8x16 > font.h && uudecode < /usr/share/syscons/fonts/${SC_DFLT_FONT}-8x14.fnt && file2c 'u_char dflt_font_14[14*256] = {' '};' < ${SC_DFLT_FONT}-8x14 >> font.h && uudecode < /usr/share/syscons/fonts/${SC_DFLT_FONT}-8x8.fnt && file2c 'u_char dflt_font_8[8*256] = {' '};' < ${SC_DFLT_FONT}-8x8 >> font.h" \ no-obj no-implicit-rule before-depend \ clean "font.h ${SC_DFLT_FONT}-8x14 ${SC_DFLT_FONT}-8x16 ${SC_DFLT_FONT}-8x8" +kern/pic_if.m optional arm_intrng kern/subr_busdma_bufalloc.c standard kern/subr_sfbuf.c standard libkern/arm/aeabi_unwind.c standard From 7481f0978ade6735f7c33cd62a00fdcbc9858dad Mon Sep 17 00:00:00 2001 From: Ed Maste Date: Thu, 14 Apr 2016 16:32:27 +0000 Subject: [PATCH 034/143] arm64 libc: hide .cerror, .curbrk, .minbrk for WITHOUT_SYMVER When symver is in use these are hidden because they're not listed in the Symbol.map. Add an explicit .hidden so they are also hidden in the WITHOUT_SYMVER case. Reviewed by: andrew Sponsored by: The FreeBSD Foundation Differential Revision: https://reviews.freebsd.org/D5775 --- lib/libc/aarch64/sys/brk.S | 1 + lib/libc/aarch64/sys/cerror.S | 1 + lib/libc/aarch64/sys/sbrk.S | 1 + 3 files changed, 3 insertions(+) diff --git a/lib/libc/aarch64/sys/brk.S b/lib/libc/aarch64/sys/brk.S index 1e9a2156476f..c403b43f98f1 100644 --- a/lib/libc/aarch64/sys/brk.S +++ b/lib/libc/aarch64/sys/brk.S @@ -37,6 +37,7 @@ __FBSDID("$FreeBSD$"); .data .align 3 .globl _C_LABEL(minbrk) + .hidden _C_LABEL(minbrk) .type _C_LABEL(minbrk),#object _C_LABEL(minbrk): .quad _C_LABEL(_end) diff --git a/lib/libc/aarch64/sys/cerror.S b/lib/libc/aarch64/sys/cerror.S index 26c61bc7cc3e..9d87275e8246 100644 --- a/lib/libc/aarch64/sys/cerror.S +++ b/lib/libc/aarch64/sys/cerror.S @@ -29,6 +29,7 @@ __FBSDID("$FreeBSD$"); ENTRY(cerror) + .hidden cerror sub sp, sp, #16 stp x0, lr, [sp] bl _C_LABEL(__error) diff --git a/lib/libc/aarch64/sys/sbrk.S b/lib/libc/aarch64/sys/sbrk.S index 4880cc2a8c9d..87b82d4ec9ea 100644 --- a/lib/libc/aarch64/sys/sbrk.S +++ b/lib/libc/aarch64/sys/sbrk.S @@ -37,6 +37,7 @@ __FBSDID("$FreeBSD$"); .data .align 3 .global _C_LABEL(curbrk) + .hidden _C_LABEL(curbrk) .type _C_LABEL(curbrk),#object _C_LABEL(curbrk): .quad _C_LABEL(_end) From a3269b0863566911ddddde56ac2db3d169085ae2 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Thu, 14 Apr 2016 17:04:06 +0000 Subject: [PATCH 035/143] x86: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/i386/i386/db_disasm.c | 14 +++++++------- sys/i386/i386/pmap.c | 6 +++--- sys/i386/ibcs2/imgact_coff.c | 6 +++--- sys/x86/x86/nexus.c | 4 ++-- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/sys/i386/i386/db_disasm.c b/sys/i386/i386/db_disasm.c index 4f771dc3e62c..2b398da8e96c 100644 --- a/sys/i386/i386/db_disasm.c +++ b/sys/i386/i386/db_disasm.c @@ -953,17 +953,17 @@ db_read_address(loc, short_addr, regmodrm, addrp) return (loc); } addrp->is_reg = FALSE; - addrp->index = 0; + addrp->index = NULL; if (short_addr) { - addrp->index = 0; + addrp->index = NULL; addrp->ss = 0; switch (mod) { case 0: if (rm == 6) { get_value_inc(disp, loc, 2, FALSE); addrp->disp = disp; - addrp->base = 0; + addrp->base = NULL; } else { addrp->disp = 0; @@ -997,7 +997,7 @@ db_read_address(loc, short_addr, regmodrm, addrp) case 0: if (rm == 5) { get_value_inc(addrp->disp, loc, 4, FALSE); - addrp->base = 0; + addrp->base = NULL; } else { addrp->disp = 0; @@ -1037,7 +1037,7 @@ db_print_address(seg, size, addrp) } db_printsym((db_addr_t)addrp->disp, DB_STGY_ANY); - if (addrp->base != 0 || addrp->index != 0) { + if (addrp->base != NULL || addrp->index != NULL) { db_printf("("); if (addrp->base) db_printf("%s", addrp->base); @@ -1171,7 +1171,7 @@ db_disasm(db_addr_t loc, bool altfmt) get_value_inc(inst, loc, 1, FALSE); short_addr = FALSE; size = LONG; - seg = 0; + seg = NULL; /* * Get prefixes @@ -1239,7 +1239,7 @@ db_disasm(db_addr_t loc, bool altfmt) if (inst == 0x0f) { get_value_inc(inst, loc, 1, FALSE); ip = db_inst_0f[inst>>4]; - if (ip == 0) { + if (ip == NULL) { ip = &db_bad_inst; } else { diff --git a/sys/i386/i386/pmap.c b/sys/i386/i386/pmap.c index 5bdc98875ca7..575e42f28d7d 100644 --- a/sys/i386/i386/pmap.c +++ b/sys/i386/i386/pmap.c @@ -269,15 +269,15 @@ pt_entry_t *CMAP3; static pd_entry_t *KPTD; caddr_t ptvmmap = 0; caddr_t CADDR3; -struct msgbuf *msgbufp = 0; +struct msgbuf *msgbufp = NULL; /* * Crashdump maps. */ static caddr_t crashdumpmap; -static pt_entry_t *PMAP1 = 0, *PMAP2; -static pt_entry_t *PADDR1 = 0, *PADDR2; +static pt_entry_t *PMAP1 = NULL, *PMAP2; +static pt_entry_t *PADDR1 = NULL, *PADDR2; #ifdef SMP static int PMAP1cpu; static int PMAP1changedcpu; diff --git a/sys/i386/ibcs2/imgact_coff.c b/sys/i386/ibcs2/imgact_coff.c index a7543d734dec..3a5611df0daa 100644 --- a/sys/i386/ibcs2/imgact_coff.c +++ b/sys/i386/ibcs2/imgact_coff.c @@ -69,7 +69,7 @@ load_coff_section(struct vmspace *vmspace, struct vnode *vp, vm_offset_t offset, vm_offset_t map_offset; vm_offset_t map_addr; int error; - unsigned char *data_buf = 0; + unsigned char *data_buf = NULL; size_t copy_len; map_offset = trunc_page(offset); @@ -163,7 +163,7 @@ coff_load_file(struct thread *td, char *name) struct filehdr *fhdr; struct aouthdr *ahdr; struct scnhdr *scns; - char *ptr = 0; + char *ptr = NULL; int nscns; unsigned long text_offset = 0, text_address = 0, text_size = 0; unsigned long data_offset = 0, data_address = 0, data_size = 0; @@ -363,7 +363,7 @@ exec_coff_imgact(imgp) /* .bss section */ bss_size = scns[i].s_size; } else if (scns[i].s_flags & STYP_LIB) { - char *buf = 0; + char *buf = NULL; int foff = trunc_page(scns[i].s_scnptr); int off = scns[i].s_scnptr - foff; int len = round_page(scns[i].s_size + PAGE_SIZE); diff --git a/sys/x86/x86/nexus.c b/sys/x86/x86/nexus.c index 8b49d41baab8..5d4c37e60802 100644 --- a/sys/x86/x86/nexus.c +++ b/sys/x86/x86/nexus.c @@ -397,7 +397,7 @@ nexus_alloc_resource(device_t bus, device_t child, int type, int *rid, return (NULL); rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) + if (rv == NULL) return 0; rman_set_rid(rv, *rid); @@ -526,7 +526,7 @@ nexus_setup_intr(device_t bus, device_t child, struct resource *irq, if (irq == NULL) panic("nexus_setup_intr: NULL irq resource!"); - *cookiep = 0; + *cookiep = NULL; if ((rman_get_flags(irq) & RF_SHAREABLE) == 0) flags |= INTR_EXCL; From 7f5b12538bae64a7125b4439a32e49ef09fd860e Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Thu, 14 Apr 2016 17:06:37 +0000 Subject: [PATCH 036/143] RPC: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/rpc/svc_vc.c | 2 +- sys/xdr/xdr_mem.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sys/rpc/svc_vc.c b/sys/rpc/svc_vc.c index 81cb75535231..58bdd011060e 100644 --- a/sys/rpc/svc_vc.c +++ b/sys/rpc/svc_vc.c @@ -416,7 +416,7 @@ svc_vc_rendezvous_recv(SVCXPRT *xprt, struct rpc_msg *msg, sx_xunlock(&xprt->xp_lock); - sa = 0; + sa = NULL; error = soaccept(so, &sa); if (error) { diff --git a/sys/xdr/xdr_mem.c b/sys/xdr/xdr_mem.c index 74bab3b2621f..8a14f17e774d 100644 --- a/sys/xdr/xdr_mem.c +++ b/sys/xdr/xdr_mem.c @@ -214,7 +214,7 @@ xdrmem_setpos(XDR *xdrs, u_int pos) static int32_t * xdrmem_inline_aligned(XDR *xdrs, u_int len) { - int32_t *buf = 0; + int32_t *buf = NULL; if (xdrs->x_handy >= len) { xdrs->x_handy -= len; From 44c16975a297fa801cbe06a843e78feb7a422cbc Mon Sep 17 00:00:00 2001 From: Jamie Gritton Date: Thu, 14 Apr 2016 17:07:26 +0000 Subject: [PATCH 037/143] Clean up some style(9) violations. --- sys/kern/uipc_mqueue.c | 4 +++- sys/kern/uipc_sem.c | 11 +++++------ sys/kern/uipc_shm.c | 11 +++++------ 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/sys/kern/uipc_mqueue.c b/sys/kern/uipc_mqueue.c index ecc9bcfef95f..e329ef25ec07 100644 --- a/sys/kern/uipc_mqueue.c +++ b/sys/kern/uipc_mqueue.c @@ -686,7 +686,8 @@ mqfs_init(struct vfsconf *vfc) EVENTHANDLER_PRI_ANY); mq_fdclose = mqueue_fdclose; p31b_setcfg(CTL_P1003_1B_MESSAGE_PASSING, _POSIX_MESSAGE_PASSING); - /* Note current jails */ + + /* Note current jails. */ mqfs_osd_jail_slot = osd_jail_register(mqfs_prison_destructor, methods); sx_slock(&allprison_lock); TAILQ_FOREACH(pr, &allprison, pr_list) @@ -1423,6 +1424,7 @@ mqfs_readdir(struct vop_readdir_args *ap) LIST_FOREACH(pn, &pd->mn_children, mn_sibling) { entry.d_reclen = sizeof(entry); + /* * Only show names within the same prison root directory * (or not associated with a prison, e.g. "." and ".."). diff --git a/sys/kern/uipc_sem.c b/sys/kern/uipc_sem.c index efaf1e03033f..0ecff7cc2bbf 100644 --- a/sys/kern/uipc_sem.c +++ b/sys/kern/uipc_sem.c @@ -271,13 +271,11 @@ ksem_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) mtx_unlock(&sem_lock); if (ks->ks_path != NULL) { sx_slock(&ksem_dict_lock); - if (ks->ks_path != NULL) - { + if (ks->ks_path != NULL) { path = ks->ks_path; pr_path = curthread->td_ucred->cr_prison->pr_path; - if (strcmp(pr_path, "/") != 0) - { - /* Return the jail-rooted pathname */ + if (strcmp(pr_path, "/") != 0) { + /* Return the jail-rooted pathname. */ pr_pathlen = strlen(pr_path); if (strncmp(path, pr_path, pr_pathlen) == 0 && path[pr_pathlen] == '/') @@ -503,7 +501,8 @@ ksem_create(struct thread *td, const char *name, semid_t *semidp, mode_t mode, } else { path = malloc(MAXPATHLEN, M_KSEM, M_WAITOK); pr_path = td->td_ucred->cr_prison->pr_path; - /* Construct a full pathname for jailed callers */ + + /* Construct a full pathname for jailed callers. */ pr_pathlen = strcmp(pr_path, "/") == 0 ? 0 : strlcpy(path, pr_path, MAXPATHLEN); error = copyinstr(name, path + pr_pathlen, diff --git a/sys/kern/uipc_shm.c b/sys/kern/uipc_shm.c index 3d78dc4e99bb..0657787006bb 100644 --- a/sys/kern/uipc_shm.c +++ b/sys/kern/uipc_shm.c @@ -727,7 +727,8 @@ kern_shm_open(struct thread *td, const char *userpath, int flags, mode_t mode, } else { path = malloc(MAXPATHLEN, M_SHMFD, M_WAITOK); pr_path = td->td_ucred->cr_prison->pr_path; - /* Construct a full pathname for jailed callers */ + + /* Construct a full pathname for jailed callers. */ pr_pathlen = strcmp(pr_path, "/") == 0 ? 0 : strlcpy(path, pr_path, MAXPATHLEN); error = copyinstr(userpath, path + pr_pathlen, @@ -1087,13 +1088,11 @@ shm_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) kif->kf_un.kf_file.kf_file_size = shmfd->shm_size; if (shmfd->shm_path != NULL) { sx_slock(&shm_dict_lock); - if (shmfd->shm_path != NULL) - { + if (shmfd->shm_path != NULL) { path = shmfd->shm_path; pr_path = curthread->td_ucred->cr_prison->pr_path; - if (strcmp(pr_path, "/") != 0) - { - /* Return the jail-rooted pathname */ + if (strcmp(pr_path, "/") != 0) { + /* Return the jail-rooted pathname. */ pr_pathlen = strlen(pr_path); if (strncmp(path, pr_path, pr_pathlen) == 0 && path[pr_pathlen] == '/') From d9ca4bc0737bb52f4baa520d54eed36348fcc062 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Thu, 14 Apr 2016 17:20:35 +0000 Subject: [PATCH 038/143] isa/pnp: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/isa/pnp.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sys/isa/pnp.c b/sys/isa/pnp.c index f2e5dfc8b87f..599af84a1770 100644 --- a/sys/isa/pnp.c +++ b/sys/isa/pnp.c @@ -416,14 +416,14 @@ static int pnp_create_devices(device_t parent, pnp_id *p, int csn, u_char *resources, int len) { - u_char tag, *resp, *resinfo, *startres = 0; + u_char tag, *resp, *resinfo, *startres = NULL; int large_len, scanning = len, retval = FALSE; uint32_t logical_id; device_t dev = 0; int ldn = 0; struct pnp_set_config_arg *csnldn; char buf[100]; - char *desc = 0; + char *desc = NULL; resp = resources; while (scanning > 0) { @@ -492,7 +492,7 @@ pnp_create_devices(device_t parent, pnp_id *p, int csn, pnp_parse_resources(dev, startres, resinfo - startres - 1, ldn); dev = 0; - startres = 0; + startres = NULL; } /* @@ -537,7 +537,7 @@ pnp_create_devices(device_t parent, pnp_id *p, int csn, pnp_parse_resources(dev, startres, resinfo - startres - 1, ldn); dev = 0; - startres = 0; + startres = NULL; scanning = 0; break; @@ -674,7 +674,7 @@ pnp_isolation_protocol(device_t parent) int csn; pnp_id id; int found = 0, len; - u_char *resources = 0; + u_char *resources = NULL; int space = 0; int error; #ifdef PC98 From b93c97c14ab6502b86085fdadc5ee8aa7ec7348c Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Thu, 14 Apr 2016 17:25:50 +0000 Subject: [PATCH 039/143] risc-v: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/riscv/riscv/nexus.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/riscv/riscv/nexus.c b/sys/riscv/riscv/nexus.c index a4ced760eeaa..75e16b881f16 100644 --- a/sys/riscv/riscv/nexus.c +++ b/sys/riscv/riscv/nexus.c @@ -242,7 +242,7 @@ nexus_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) + if (rv == NULL) return (NULL); rman_set_rid(rv, *rid); From ce2761f128edb3f1962d2eeadad80001ac457c60 Mon Sep 17 00:00:00 2001 From: Mark Johnston Date: Thu, 14 Apr 2016 18:03:55 +0000 Subject: [PATCH 040/143] Include -a in the nextboot(8) usage string. X-MFC-With: r297772 --- sbin/reboot/nextboot.8 | 3 +-- sbin/reboot/nextboot.sh | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/sbin/reboot/nextboot.8 b/sbin/reboot/nextboot.8 index d006c3f20c0b..8b72b9ad10de 100644 --- a/sbin/reboot/nextboot.8 +++ b/sbin/reboot/nextboot.8 @@ -32,9 +32,8 @@ .Nd "specify an alternate kernel and boot flags for the next reboot" .Sh SYNOPSIS .Nm -.Op Fl a +.Op Fl af .Op Fl e Ar variable=value -.Op Fl f .Op Fl k Ar kernel .Op Fl o Ar options .Nm diff --git a/sbin/reboot/nextboot.sh b/sbin/reboot/nextboot.sh index a90fdebae217..d9bbb259e31e 100644 --- a/sbin/reboot/nextboot.sh +++ b/sbin/reboot/nextboot.sh @@ -50,7 +50,7 @@ add_kenv() display_usage() { cat <<-EOF - Usage: nextboot [-e variable=value] [-f] [-k kernel] [-o options] + Usage: nextboot [-af] [-e variable=value] [-k kernel] [-o options] nextboot -D EOF } From 7b34dbe450dbf5092a528928ad4dbb7751ad3e88 Mon Sep 17 00:00:00 2001 From: "Andrey V. Elsukov" Date: Thu, 14 Apr 2016 18:22:08 +0000 Subject: [PATCH 041/143] Fix output formatting of O_UNREACH6 opcode. Obtained from: Yandex LLC --- sbin/ipfw/ipfw2.c | 2 +- sbin/ipfw/ipfw2.h | 2 +- sbin/ipfw/ipv6.c | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/sbin/ipfw/ipfw2.c b/sbin/ipfw/ipfw2.c index 95a96adb18b2..74198b63584f 100644 --- a/sbin/ipfw/ipfw2.c +++ b/sbin/ipfw/ipfw2.c @@ -1484,7 +1484,7 @@ show_static_rule(struct cmdline_opts *co, struct format_opts *fo, if (cmd->arg1 == ICMP6_UNREACH_RST) bprintf(bp, "reset6"); else - print_unreach6_code(cmd->arg1); + print_unreach6_code(bp, cmd->arg1); break; case O_SKIPTO: diff --git a/sbin/ipfw/ipfw2.h b/sbin/ipfw/ipfw2.h index 86f2a41733f5..03c91e5672fd 100644 --- a/sbin/ipfw/ipfw2.h +++ b/sbin/ipfw/ipfw2.h @@ -329,7 +329,7 @@ void dummynet_flush(void); int ipfw_delete_pipe(int pipe_or_queue, int n); /* ipv6.c */ -void print_unreach6_code(uint16_t code); +void print_unreach6_code(struct buf_pr *bp, uint16_t code); void print_ip6(struct buf_pr *bp, struct _ipfw_insn_ip6 *cmd, char const *s); void print_flow6id(struct buf_pr *bp, struct _ipfw_insn_u32 *cmd); void print_icmp6types(struct buf_pr *bp, struct _ipfw_insn_u32 *cmd); diff --git a/sbin/ipfw/ipv6.c b/sbin/ipfw/ipv6.c index 36ee675bdf9a..c04dd702b93d 100644 --- a/sbin/ipfw/ipv6.c +++ b/sbin/ipfw/ipv6.c @@ -71,14 +71,14 @@ fill_unreach6_code(u_short *codep, char *str) } void -print_unreach6_code(uint16_t code) +print_unreach6_code(struct buf_pr *bp, uint16_t code) { char const *s = match_value(icmp6codes, code); if (s != NULL) - printf("unreach6 %s", s); + bprintf(bp, "unreach6 %s", s); else - printf("unreach6 %u", code); + bprintf(bp, "unreach6 %u", code); } /* From 7f6a709bef784b87a704b44c08a7790446109c35 Mon Sep 17 00:00:00 2001 From: Mariusz Zaborski Date: Thu, 14 Apr 2016 18:27:10 +0000 Subject: [PATCH 042/143] Set NULL to the ai_next pointer which fix cap_getaddrinfo(). Add regression test case. PR: 195551 Submitted by: Mikhail Approved by: pjd (mentor) --- lib/libcasper/services/cap_dns/cap_dns.c | 1 + tools/regression/capsicum/libcasper/dns.c | 130 ++++++++++++++++++++-- 2 files changed, 123 insertions(+), 8 deletions(-) diff --git a/lib/libcasper/services/cap_dns/cap_dns.c b/lib/libcasper/services/cap_dns/cap_dns.c index 873af4cdcdde..0ecf047027b2 100644 --- a/lib/libcasper/services/cap_dns/cap_dns.c +++ b/lib/libcasper/services/cap_dns/cap_dns.c @@ -632,6 +632,7 @@ dns_getaddrinfo(const nvlist_t *limits, const nvlist_t *nvlin, nvlist_t *nvlout) hints.ai_addrlen = 0; hints.ai_addr = NULL; hints.ai_canonname = NULL; + hints.ai_next = NULL; hintsp = &hints; family = hints.ai_family; } else { diff --git a/tools/regression/capsicum/libcasper/dns.c b/tools/regression/capsicum/libcasper/dns.c index eb364daf8cd2..51839c161c1c 100644 --- a/tools/regression/capsicum/libcasper/dns.c +++ b/tools/regression/capsicum/libcasper/dns.c @@ -72,6 +72,63 @@ static int ntest = 1; #define GETHOSTBYNAME2_AF_INET6 0x04 #define GETHOSTBYADDR_AF_INET 0x08 #define GETHOSTBYADDR_AF_INET6 0x10 +#define GETADDRINFO_AF_UNSPEC 0x20 +#define GETADDRINFO_AF_INET 0x40 +#define GETADDRINFO_AF_INET6 0x80 + +static bool +addrinfo_compare(struct addrinfo *ai0, struct addrinfo *ai1) +{ + struct addrinfo *at0, *at1; + + if (ai0 == NULL && ai1 == NULL) + return (true); + if (ai0 == NULL || ai1 == NULL) + return (false); + + at0 = ai0; + at1 = ai1; + while (true) { + if ((at0->ai_flags == at1->ai_flags) && + (at0->ai_family == at1->ai_family) && + (at0->ai_socktype == at1->ai_socktype) && + (at0->ai_protocol == at1->ai_protocol) && + (at0->ai_addrlen == at1->ai_addrlen) && + (memcmp(at0->ai_addr, at1->ai_addr, + at0->ai_addrlen) == 0)) { + if (at0->ai_canonname != NULL && + at1->ai_canonname != NULL) { + if (strcmp(at0->ai_canonname, + at1->ai_canonname) != 0) { + return (false); + } + } + + if (at0->ai_canonname == NULL && + at1->ai_canonname != NULL) { + return (false); + } + if (at0->ai_canonname != NULL && + at1->ai_canonname == NULL) { + return (false); + } + + if (at0->ai_next == NULL && at1->ai_next == NULL) + return (true); + if (at0->ai_next == NULL || at1->ai_next == NULL) + return (false); + + at0 = at0->ai_next; + at1 = at1->ai_next; + } else { + return (false); + } + } + + /* NOTREACHED */ + fprintf(stderr, "Dead code reached in addrinfo_compare()\n"); + exit(1); +} static bool hostent_aliases_compare(char **aliases0, char **aliases1) @@ -161,6 +218,7 @@ static unsigned int runtest(cap_channel_t *capdns) { unsigned int result; + struct addrinfo *ais, *aic, hints, *hintsp; struct hostent *hps, *hpc; struct in_addr ip4; struct in6_addr ip6; @@ -188,6 +246,55 @@ runtest(cap_channel_t *capdns) if (hostent_compare(hps, hpc)) result |= GETHOSTBYNAME2_AF_INET6; + hints.ai_flags = 0; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = 0; + hints.ai_protocol = 0; + hints.ai_addrlen = 0; + hints.ai_addr = NULL; + hints.ai_canonname = NULL; + hints.ai_next = NULL; + + hintsp = &hints; + + if (getaddrinfo("freebsd.org", "25", hintsp, &ais) != 0) { + fprintf(stderr, + "Unable to issue [system] getaddrinfo() for AF_UNSPEC: %s\n", + gai_strerror(errno)); + } + if (cap_getaddrinfo(capdns, "freebsd.org", "25", hintsp, &aic) == 0) { + if (addrinfo_compare(ais, aic)) + result |= GETADDRINFO_AF_UNSPEC; + freeaddrinfo(ais); + freeaddrinfo(aic); + } + + hints.ai_family = AF_INET; + if (getaddrinfo("freebsd.org", "25", hintsp, &ais) != 0) { + fprintf(stderr, + "Unable to issue [system] getaddrinfo() for AF_UNSPEC: %s\n", + gai_strerror(errno)); + } + if (cap_getaddrinfo(capdns, "freebsd.org", "25", hintsp, &aic) == 0) { + if (addrinfo_compare(ais, aic)) + result |= GETADDRINFO_AF_INET; + freeaddrinfo(ais); + freeaddrinfo(aic); + } + + hints.ai_family = AF_INET6; + if (getaddrinfo("freebsd.org", "25", hintsp, &ais) != 0) { + fprintf(stderr, + "Unable to issue [system] getaddrinfo() for AF_UNSPEC: %s\n", + gai_strerror(errno)); + } + if (cap_getaddrinfo(capdns, "freebsd.org", "25", hintsp, &aic) == 0) { + if (addrinfo_compare(ais, aic)) + result |= GETADDRINFO_AF_INET6; + freeaddrinfo(ais); + freeaddrinfo(aic); + } + /* * 8.8.178.135 is IPv4 address of freefall.freebsd.org * as of 27 October 2013. @@ -238,7 +345,8 @@ main(void) CHECK(runtest(capdns) == (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET | GETHOSTBYNAME2_AF_INET6 | - GETHOSTBYADDR_AF_INET | GETHOSTBYADDR_AF_INET6)); + GETHOSTBYADDR_AF_INET | GETHOSTBYADDR_AF_INET6 | + GETADDRINFO_AF_UNSPEC | GETADDRINFO_AF_INET | GETADDRINFO_AF_INET6)); /* * Allow: @@ -258,7 +366,8 @@ main(void) CHECK(runtest(capdns) == (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET | GETHOSTBYNAME2_AF_INET6 | - GETHOSTBYADDR_AF_INET | GETHOSTBYADDR_AF_INET6)); + GETHOSTBYADDR_AF_INET | GETHOSTBYADDR_AF_INET6 | + GETADDRINFO_AF_INET | GETADDRINFO_AF_INET6)); cap_close(capdns); @@ -310,7 +419,8 @@ main(void) CHECK(cap_dns_family_limit(capdns, families, 2) == 0); CHECK(runtest(capdns) == - (GETHOSTBYADDR_AF_INET | GETHOSTBYADDR_AF_INET6)); + (GETHOSTBYADDR_AF_INET | GETHOSTBYADDR_AF_INET6 | + GETADDRINFO_AF_INET | GETADDRINFO_AF_INET6)); cap_close(capdns); @@ -336,7 +446,8 @@ main(void) errno == ENOTCAPABLE); CHECK(runtest(capdns) == - (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET | GETHOSTBYADDR_AF_INET)); + (GETHOSTBYNAME | GETHOSTBYNAME2_AF_INET | GETHOSTBYADDR_AF_INET | + GETADDRINFO_AF_INET)); cap_close(capdns); @@ -362,7 +473,8 @@ main(void) errno == ENOTCAPABLE); CHECK(runtest(capdns) == - (GETHOSTBYNAME2_AF_INET6 | GETHOSTBYADDR_AF_INET6)); + (GETHOSTBYNAME2_AF_INET6 | GETHOSTBYADDR_AF_INET6 | + GETADDRINFO_AF_INET6)); cap_close(capdns); @@ -472,7 +584,7 @@ main(void) CHECK(cap_dns_family_limit(capdns, families, 1) == -1 && errno == ENOTCAPABLE); - CHECK(runtest(capdns) == GETHOSTBYADDR_AF_INET); + CHECK(runtest(capdns) == (GETHOSTBYADDR_AF_INET | GETADDRINFO_AF_INET)); cap_close(capdns); @@ -508,7 +620,8 @@ main(void) CHECK(cap_dns_family_limit(capdns, families, 1) == -1 && errno == ENOTCAPABLE); - CHECK(runtest(capdns) == GETHOSTBYADDR_AF_INET6); + CHECK(runtest(capdns) == (GETHOSTBYADDR_AF_INET6 | + GETADDRINFO_AF_INET6)); cap_close(capdns); @@ -578,7 +691,8 @@ main(void) errno == ENOTCAPABLE); /* Do the limits still hold? */ - CHECK(runtest(capdns) == GETHOSTBYADDR_AF_INET6); + CHECK(runtest(capdns) == (GETHOSTBYADDR_AF_INET6 | + GETADDRINFO_AF_INET6)); cap_close(capdns); From ab341f7afdb9ec23ad4207ea0b0835d12e95313b Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Thu, 14 Apr 2016 18:31:45 +0000 Subject: [PATCH 043/143] libpcap: fix for simple NULL pointer dereference. Found with devel/coccinelle. --- contrib/libpcap/pcap-snf.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contrib/libpcap/pcap-snf.c b/contrib/libpcap/pcap-snf.c index ee6ffa4dcc6e..b8025ba8ba89 100644 --- a/contrib/libpcap/pcap-snf.c +++ b/contrib/libpcap/pcap-snf.c @@ -57,10 +57,11 @@ snf_pcap_stats(pcap_t *p, struct pcap_stat *ps) static void snf_platform_cleanup(pcap_t *p) { - struct pcap_snf *ps = p->priv; + struct pcap_snf *ps; if (p == NULL) return; + ps = p->priv; snf_ring_close(ps->snf_ring); snf_close(ps->snf_handle); From db1bbde602dd439c6de30121dd3304f6e98cd9c3 Mon Sep 17 00:00:00 2001 From: Luiz Otavio O Souza Date: Thu, 14 Apr 2016 18:37:40 +0000 Subject: [PATCH 044/143] Make pfctl(8) more flexible when parsing bandwidth values. This is the current behaviour in OpenBSD and a similar patch exist in pfSense too. Obtained from: OpenBSD (partly - rev. 1.625) MFC after: 2 weeks Sponsored by: Rubicon Communications (Netgate) --- sbin/pfctl/parse.y | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/sbin/pfctl/parse.y b/sbin/pfctl/parse.y index 9b22a6b032cc..a03ddbcfa3be 100644 --- a/sbin/pfctl/parse.y +++ b/sbin/pfctl/parse.y @@ -1605,13 +1605,22 @@ bandwidth : STRING { bps = strtod($1, &cp); if (cp != NULL) { + if (strlen(cp) > 1) { + char *cu = cp + 1; + if (!strcmp(cu, "Bit") || + !strcmp(cu, "B") || + !strcmp(cu, "bit") || + !strcmp(cu, "b")) { + *cu = 0; + } + } if (!strcmp(cp, "b")) ; /* nothing */ - else if (!strcmp(cp, "Kb")) + else if (!strcmp(cp, "K")) bps *= 1000; - else if (!strcmp(cp, "Mb")) + else if (!strcmp(cp, "M")) bps *= 1000 * 1000; - else if (!strcmp(cp, "Gb")) + else if (!strcmp(cp, "G")) bps *= 1000 * 1000 * 1000; else if (!strcmp(cp, "%")) { if (bps < 0 || bps > 100) { From de89d74b70d1d169871785d89df32a2459edcee9 Mon Sep 17 00:00:00 2001 From: Luiz Otavio O Souza Date: Thu, 14 Apr 2016 18:57:30 +0000 Subject: [PATCH 045/143] Do not overwrite the dchg variable. It does not cause any real issues because the variable is overwritten only when the packet is forwarded (and the variable is not used anymore). Obtained from: pfSense MFC after: 2 weeks Sponsored by: Rubicon Communications (Netgate) --- sys/netinet/ip_input.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/sys/netinet/ip_input.c b/sys/netinet/ip_input.c index 6f25e08b33f0..773d7aeb807a 100644 --- a/sys/netinet/ip_input.c +++ b/sys/netinet/ip_input.c @@ -571,8 +571,7 @@ ip_input(struct mbuf *m) goto ours; } if (m->m_flags & M_IP_NEXTHOP) { - dchg = (m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL); - if (dchg != 0) { + if (m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL) { /* * Directly ship the packet on. This allows * forwarding packets originally destined to us From f0ac0530882177efbe90f41425f65fb212b2b63d Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Thu, 14 Apr 2016 19:20:31 +0000 Subject: [PATCH 046/143] Update a debugging message in vdev_geom_open_by_guids for consistency with similar messages elsewhere in the file. MFC after: 4 weeks Sponsored by: Spectra Logic Corp --- sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c index 1777fbab856c..edea99f97169 100644 --- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c +++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c @@ -625,7 +625,8 @@ vdev_geom_open_by_guids(vdev_t *vd) g_topology_assert(); - ZFS_LOG(1, "Searching by guid [%ju].", (uintmax_t)vd->vdev_guid); + ZFS_LOG(1, "Searching by guids [%ju:%ju].", + (uintmax_t)spa_guid(vd->vdev_spa), (uintmax_t)vd->vdev_guid); cp = vdev_geom_attach_by_guids(vd); if (cp != NULL) { len = strlen(cp->provider->name) + strlen("/dev/") + 1; From add7a95518314ed8571c59a5d4b7955e7b8adcec Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 19:26:29 +0000 Subject: [PATCH 047/143] Follow-up r284673: /usr/lib32/libc_pic.a is still installed, just not the profiled libs. Sponsored by: EMC / Isilon Storage Division --- ObsoleteFiles.inc | 1 - 1 file changed, 1 deletion(-) diff --git a/ObsoleteFiles.inc b/ObsoleteFiles.inc index 5f29f4b3048c..d1cfd7f34c9e 100644 --- a/ObsoleteFiles.inc +++ b/ObsoleteFiles.inc @@ -1732,7 +1732,6 @@ OLD_FILES+=usr/share/man/man4/lindev.4.gz # 20140425 OLD_FILES+=usr/lib/libssp_p.a OLD_FILES+=usr/lib/libstand_p.a -OLD_FILES+=usr/lib32/libc_pic.a OLD_FILES+=usr/lib32/libssp_p.a OLD_FILES+=usr/lib32/libstand_p.a # 20140314: AppleTalk From 9b8f7eaf6ae86bd049080230df51b071095ab1bf Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 19:29:35 +0000 Subject: [PATCH 048/143] Define the *soft targets properly. Sponsored by: EMC / Isilon Storage Division --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 4e4b6c454076..2e4e6763d7a8 100644 --- a/Makefile +++ b/Makefile @@ -125,7 +125,7 @@ TGTS= all all-man buildenv buildenvvars buildkernel buildworld \ obj objlink rerelease showconfig tags toolchain update \ _worldtmp _legacy _bootstrap-tools _cleanobj _obj \ _build-tools _cross-tools _includes _libraries \ - build32 distribute32 install32 build32 distribute32 install32 \ + build32 distribute32 install32 buildsoft distributesoft installsoft \ builddtb xdev xdev-build xdev-install \ xdev-links native-xtools installconfig \ From f77b842746f3eef29437d17b7f37607f8ec06990 Mon Sep 17 00:00:00 2001 From: Michael Tuexen Date: Thu, 14 Apr 2016 19:51:29 +0000 Subject: [PATCH 049/143] When delivering an ICMP packet to the ctlinput function, ensure that the outer IP header, the ICMP header, the inner IP header and the first n bytes are stored in contgous memory. The ctlinput functions currently rely on this for n = 8. This fixes a bug in case the inner IP header had options. While there, remove the options from the outer header and provide a way to increase n to allow improved ICMP handling for SCTP. This will be added in another commit. MFC after: 1 week --- sys/netinet/ip_icmp.c | 17 +++++++++++++++++ sys/netinet/ip_icmp.h | 6 ++++++ 2 files changed, 23 insertions(+) diff --git a/sys/netinet/ip_icmp.c b/sys/netinet/ip_icmp.c index 6e6202a00420..cc3e1f514f93 100644 --- a/sys/netinet/ip_icmp.c +++ b/sys/netinet/ip_icmp.c @@ -475,6 +475,23 @@ icmp_input(struct mbuf **mp, int *offp, int proto) * XXX if the packet contains [IPv4 AH TCP], we can't make a * notification to TCP layer. */ + i = sizeof(struct ip) + min(icmplen, ICMP_ADVLENPREF(icp)); + ip_stripoptions(m); + if (m->m_len < i && (m = m_pullup(m, i)) == NULL) { + /* This should actually not happen */ + ICMPSTAT_INC(icps_tooshort); + return (IPPROTO_DONE); + } + ip = mtod(m, struct ip *); + icp = (struct icmp *)(ip + 1); + /* + * The upper layer handler can rely on: + * - The outer IP header has no options. + * - The outer IP header, the ICMP header, the inner IP header, + * and the first n bytes of the inner payload are contiguous. + * n is at least 8, but might be larger based on + * ICMP_ADVLENPREF. See its definition in ip_icmp.h. + */ ctlfunc = inetsw[ip_protox[icp->icmp_ip.ip_p]].pr_ctlinput; if (ctlfunc) (*ctlfunc)(code, (struct sockaddr *)&icmpsrc, diff --git a/sys/netinet/ip_icmp.h b/sys/netinet/ip_icmp.h index 38d44d78617d..e69bfe1f9a9d 100644 --- a/sys/netinet/ip_icmp.h +++ b/sys/netinet/ip_icmp.h @@ -136,6 +136,12 @@ struct icmp { #define ICMP_ADVLENMIN (8 + sizeof (struct ip) + 8) /* min */ #define ICMP_ADVLEN(p) (8 + ((p)->icmp_ip.ip_hl << 2) + 8) /* N.B.: must separately check that ip_hl >= 5 */ + /* This is the minimum length required by RFC 792. */ +/* + * ICMP_ADVLENPREF is the preferred number of bytes which should be contiguous. + * It currently reflects the required minimum. + */ +#define ICMP_ADVLENPREF(p) (8 + ((p)->icmp_ip.ip_hl << 2) + 8) /* * Definition of type and code field values. From 4d6b853ad67584878fd0783288970eeb7cc511f4 Mon Sep 17 00:00:00 2001 From: Michael Tuexen Date: Thu, 14 Apr 2016 19:59:21 +0000 Subject: [PATCH 050/143] Allow the handling of ICMP messages sent in response to SCTP packets containing an INIT chunk. These need to be handled in case the peer does not support SCTP and returns an ICMP messages indicating destination unreachable, protocol unreachable. MFC after: 1 week --- sys/netinet/ip_icmp.h | 5 +-- sys/netinet/sctp_usrreq.c | 72 +++++++++++++++++++++++---------------- 2 files changed, 45 insertions(+), 32 deletions(-) diff --git a/sys/netinet/ip_icmp.h b/sys/netinet/ip_icmp.h index e69bfe1f9a9d..a04643294ae2 100644 --- a/sys/netinet/ip_icmp.h +++ b/sys/netinet/ip_icmp.h @@ -139,9 +139,10 @@ struct icmp { /* This is the minimum length required by RFC 792. */ /* * ICMP_ADVLENPREF is the preferred number of bytes which should be contiguous. - * It currently reflects the required minimum. + * SCTP needs additional 12 bytes to be able to access the initiate tag + * in packets containing an INIT chunk. */ -#define ICMP_ADVLENPREF(p) (8 + ((p)->icmp_ip.ip_hl << 2) + 8) +#define ICMP_ADVLENPREF(p) (8 + ((p)->icmp_ip.ip_hl << 2) + 8 + 12) /* * Definition of type and code field values. diff --git a/sys/netinet/sctp_usrreq.c b/sys/netinet/sctp_usrreq.c index 5f43234af59e..1b23abca7f10 100644 --- a/sys/netinet/sctp_usrreq.c +++ b/sys/netinet/sctp_usrreq.c @@ -254,48 +254,49 @@ sctp_notify(struct sctp_inpcb *inp, void sctp_ctlinput(int cmd, struct sockaddr *sa, void *vip) { - struct ip *ip = vip; + struct ip *outer_ip, *inner_ip; struct sctphdr *sh; - struct icmp *icmph; - uint32_t vrf_id; + struct icmp *icmp; + struct sctp_inpcb *inp; + struct sctp_tcb *stcb; + struct sctp_nets *net; + struct sctp_init_chunk *ch; + struct sockaddr_in to, from; - /* FIX, for non-bsd is this right? */ - vrf_id = SCTP_DEFAULT_VRFID; if (sa->sa_family != AF_INET || ((struct sockaddr_in *)sa)->sin_addr.s_addr == INADDR_ANY) { return; } if (PRC_IS_REDIRECT(cmd)) { - ip = 0; + vip = NULL; } else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0) { return; } - if (ip) { - struct sctp_inpcb *inp = NULL; - struct sctp_tcb *stcb = NULL; - struct sctp_nets *net = NULL; - struct sockaddr_in to, from; - - icmph = (struct icmp *)((caddr_t)ip - (sizeof(struct icmp) - - sizeof(struct ip))); - - sh = (struct sctphdr *)((caddr_t)ip + (ip->ip_hl << 2)); + if (vip != NULL) { + inner_ip = (struct ip *)vip; + icmp = (struct icmp *)((caddr_t)inner_ip - + (sizeof(struct icmp) - sizeof(struct ip))); + outer_ip = (struct ip *)((caddr_t)icmp - sizeof(struct ip)); + sh = (struct sctphdr *)((caddr_t)inner_ip + (inner_ip->ip_hl << 2)); bzero(&to, sizeof(to)); bzero(&from, sizeof(from)); from.sin_family = to.sin_family = AF_INET; from.sin_len = to.sin_len = sizeof(to); from.sin_port = sh->src_port; - from.sin_addr = ip->ip_src; + from.sin_addr = inner_ip->ip_src; to.sin_port = sh->dest_port; - to.sin_addr = ip->ip_dst; + to.sin_addr = inner_ip->ip_dst; /* * 'to' holds the dest of the packet that failed to be sent. * 'from' holds our local endpoint address. Thus we reverse * the to and the from in the lookup. */ + inp = NULL; + net = NULL; stcb = sctp_findassociation_addr_sa((struct sockaddr *)&to, (struct sockaddr *)&from, - &inp, &net, 1, vrf_id); + &inp, &net, 1, + SCTP_DEFAULT_VRFID); if ((stcb != NULL) && (net != NULL) && (inp != NULL) && @@ -313,19 +314,30 @@ sctp_ctlinput(int cmd, struct sockaddr *sa, void *vip) return; } } else { - /* - * In this case we could check if we got an - * INIT chunk and if the initiate tag - * matches. But this is not there yet... - */ - SCTP_TCB_UNLOCK(stcb); - return; + if (ntohs(outer_ip->ip_len) >= + sizeof(struct ip) + + 8 + (inner_ip->ip_hl << 2) + 20) { + /* + * In this case we can check if we + * got an INIT chunk and if the + * initiate tag matches. + */ + ch = (struct sctp_init_chunk *)(sh + 1); + if ((ch->ch.chunk_type != SCTP_INITIATION) || + (ntohl(ch->init.initiate_tag) != stcb->asoc.my_vtag)) { + SCTP_TCB_UNLOCK(stcb); + return; + } + } else { + SCTP_TCB_UNLOCK(stcb); + return; + } } sctp_notify(inp, stcb, net, - icmph->icmp_type, - icmph->icmp_code, - ntohs(ip->ip_len), - ntohs(icmph->icmp_nextmtu)); + icmp->icmp_type, + icmp->icmp_code, + ntohs(inner_ip->ip_len), + ntohs(icmp->icmp_nextmtu)); } else { if ((stcb == NULL) && (inp != NULL)) { /* reduce ref-count */ From 212fad7469282057732176d62849e90e0d2de57c Mon Sep 17 00:00:00 2001 From: Alexander Motin Date: Thu, 14 Apr 2016 20:49:01 +0000 Subject: [PATCH 051/143] Extract virtual port address from RQSTYPE_RPT_ID_ACQ. This should close the race between request arriving on new target mode virtual port and its scanner thread finally fetch its address for request routing. --- sys/dev/isp/isp.c | 16 ++++++++++++---- sys/dev/isp/isp_library.c | 5 +++-- sys/dev/isp/ispvar.h | 17 +++++++++-------- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/sys/dev/isp/isp.c b/sys/dev/isp/isp.c index dd8112f6703e..01d7cbb70fdd 100644 --- a/sys/dev/isp/isp.c +++ b/sys/dev/isp/isp.c @@ -3011,7 +3011,6 @@ isp_fclink_test(ispsoftc_t *isp, int chan, int usdelay) return (0); isp_prt(isp, ISP_LOG_SANCFG, "Chan %d FC link test", chan); - fcp->isp_loopstate = LOOP_TESTING_LINK; /* * Wait up to N microseconds for F/W to go to a ready state. @@ -3022,7 +3021,7 @@ isp_fclink_test(ispsoftc_t *isp, int chan, int usdelay) if (fcp->isp_fwstate == FW_READY) { break; } - if (fcp->isp_loopstate < LOOP_TESTING_LINK) + if (fcp->isp_loopstate < LOOP_HAVE_LINK) goto abort; GET_NANOTIME(&hrb); if ((NANOTIME_SUB(&hrb, &hra) / 1000 + 1000 >= usdelay)) @@ -3077,6 +3076,11 @@ isp_fclink_test(ispsoftc_t *isp, int chan, int usdelay) fcp->isp_loopid = i; } +#if 0 + fcp->isp_loopstate = LOOP_HAVE_ADDR; +#endif + fcp->isp_loopstate = LOOP_TESTING_LINK; + if (fcp->isp_topo == TOPO_F_PORT || fcp->isp_topo == TOPO_FL_PORT) { nphdl = IS_24XX(isp) ? NPH_FL_ID : FL_ID; r = isp_getpdb(isp, chan, nphdl, &pdb); @@ -6138,7 +6142,7 @@ isp_handle_other_response(ispsoftc_t *isp, int type, isphdr_t *hp, uint32_t *opt { isp_ridacq_t rid; int chan, c; - uint32_t hdl; + uint32_t hdl, portid; void *ptr; switch (type) { @@ -6150,6 +6154,8 @@ isp_handle_other_response(ispsoftc_t *isp, int type, isphdr_t *hp, uint32_t *opt return (1); case RQSTYPE_RPT_ID_ACQ: isp_get_ridacq(isp, (isp_ridacq_t *)hp, &rid); + portid = (uint32_t)rid.ridacq_vp_port_hi << 16 | + rid.ridacq_vp_port_lo; if (rid.ridacq_format == 0) { for (chan = 0; chan < isp->isp_nchan; chan++) { fcparam *fcp = FCPARAM(isp, chan); @@ -6171,7 +6177,9 @@ isp_handle_other_response(ispsoftc_t *isp, int type, isphdr_t *hp, uint32_t *opt fcparam *fcp = FCPARAM(isp, rid.ridacq_vp_index); if (rid.ridacq_vp_status == RIDACQ_STS_COMPLETE || rid.ridacq_vp_status == RIDACQ_STS_CHANGED) { - fcp->isp_loopstate = LOOP_HAVE_LINK; + fcp->isp_topo = (rid.ridacq_map[0] >> 9) & 0x7; + fcp->isp_portid = portid; + fcp->isp_loopstate = LOOP_HAVE_ADDR; isp_async(isp, ISPASYNC_CHANGE_NOTIFY, rid.ridacq_vp_index, ISPASYNC_CHANGE_OTHER); } else { diff --git a/sys/dev/isp/isp_library.c b/sys/dev/isp/isp_library.c index c7bce2d95b64..48e053535355 100644 --- a/sys/dev/isp/isp_library.c +++ b/sys/dev/isp/isp_library.c @@ -532,6 +532,7 @@ isp_fc_loop_statename(int state) switch (state) { case LOOP_NIL: return "NIL"; case LOOP_HAVE_LINK: return "Have Link"; + case LOOP_HAVE_ADDR: return "Have Address"; case LOOP_TESTING_LINK: return "Testing Link"; case LOOP_LTEST_DONE: return "Link Test Done"; case LOOP_SCANNING_LOOP: return "Scanning Loop"; @@ -548,7 +549,7 @@ const char * isp_fc_toponame(fcparam *fcp) { - if (fcp->isp_loopstate < LOOP_LTEST_DONE) { + if (fcp->isp_loopstate < LOOP_HAVE_ADDR) { return "Unavailable"; } switch (fcp->isp_topo) { @@ -2329,7 +2330,7 @@ isp_find_chan_by_did(ispsoftc_t *isp, uint32_t did, uint16_t *cp) for (chan = 0; chan < isp->isp_nchan; chan++) { fcparam *fcp = FCPARAM(isp, chan); if ((fcp->role & ISP_ROLE_TARGET) == 0 || - fcp->isp_loopstate < LOOP_LTEST_DONE) { + fcp->isp_loopstate < LOOP_HAVE_ADDR) { continue; } if (fcp->isp_portid == did) { diff --git a/sys/dev/isp/ispvar.h b/sys/dev/isp/ispvar.h index 104782b6def8..a97a04fa0ac3 100644 --- a/sys/dev/isp/ispvar.h +++ b/sys/dev/isp/ispvar.h @@ -490,14 +490,15 @@ typedef struct { #define LOOP_NIL 0 #define LOOP_HAVE_LINK 1 -#define LOOP_TESTING_LINK 2 -#define LOOP_LTEST_DONE 3 -#define LOOP_SCANNING_LOOP 4 -#define LOOP_LSCAN_DONE 5 -#define LOOP_SCANNING_FABRIC 6 -#define LOOP_FSCAN_DONE 7 -#define LOOP_SYNCING_PDB 8 -#define LOOP_READY 9 +#define LOOP_HAVE_ADDR 2 +#define LOOP_TESTING_LINK 3 +#define LOOP_LTEST_DONE 4 +#define LOOP_SCANNING_LOOP 5 +#define LOOP_LSCAN_DONE 6 +#define LOOP_SCANNING_FABRIC 7 +#define LOOP_FSCAN_DONE 8 +#define LOOP_SYNCING_PDB 9 +#define LOOP_READY 10 #define TOPO_NL_PORT 0 #define TOPO_FL_PORT 1 From f976a4edc08ce9a5510a1189a0e6c6c70eb59ebf Mon Sep 17 00:00:00 2001 From: "Andrey V. Elsukov" Date: Thu, 14 Apr 2016 20:49:27 +0000 Subject: [PATCH 052/143] Move several functions related to opcode rewriting framework from ip_fw_table.c into ip_fw_sockopt.c and make them static. Obtained from: Yandex LLC --- sys/netpfil/ipfw/ip_fw_private.h | 8 -- sys/netpfil/ipfw/ip_fw_sockopt.c | 143 ++++++++++++++++++++++++++++++- sys/netpfil/ipfw/ip_fw_table.c | 130 ---------------------------- 3 files changed, 141 insertions(+), 140 deletions(-) diff --git a/sys/netpfil/ipfw/ip_fw_private.h b/sys/netpfil/ipfw/ip_fw_private.h index 7be3d1e815d7..659af35fdd2c 100644 --- a/sys/netpfil/ipfw/ip_fw_private.h +++ b/sys/netpfil/ipfw/ip_fw_private.h @@ -685,14 +685,6 @@ void ipfw_destroy_obj_rewriter(void); void ipfw_add_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count); int ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count); -int ipfw_rewrite_rule_uidx(struct ip_fw_chain *chain, - struct rule_check_info *ci); -int ipfw_mark_object_kidx(struct ip_fw_chain *chain, struct ip_fw *rule, - uint32_t *bmask); -int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti, - struct obj_idx *pidx, int *found, int *unresolved); -void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, - struct obj_idx *oib, struct obj_idx *end); int create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib, struct obj_idx *pidx, struct tid_info *ti); void update_opcode_kidx(ipfw_insn *cmd, uint16_t idx); diff --git a/sys/netpfil/ipfw/ip_fw_sockopt.c b/sys/netpfil/ipfw/ip_fw_sockopt.c index 857b465515ba..18f2f193dcd8 100644 --- a/sys/netpfil/ipfw/ip_fw_sockopt.c +++ b/sys/netpfil/ipfw/ip_fw_sockopt.c @@ -81,6 +81,8 @@ static int check_ipfw_rule1(struct ip_fw_rule *rule, int size, struct rule_check_info *ci); static int check_ipfw_rule0(struct ip_fw_rule0 *rule, int size, struct rule_check_info *ci); +static int rewrite_rule_uidx(struct ip_fw_chain *chain, + struct rule_check_info *ci); #define NAMEDOBJ_HASH_SIZE 32 @@ -156,7 +158,13 @@ set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule); struct opcode_obj_rewrite *ipfw_find_op_rw(uint16_t opcode); static int mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule, uint32_t *bmask); +static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule, + struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti); +static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, + struct tid_info *ti, struct obj_idx *pidx, int *found, int *unresolved); static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule); +static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, + struct obj_idx *oib, struct obj_idx *end); static int export_objhash_ntlv(struct namedobj_instance *ni, uint16_t kidx, struct sockopt_data *sd); @@ -675,7 +683,7 @@ commit_rules(struct ip_fw_chain *chain, struct rule_check_info *rci, int count) * We need to find (and create non-existing) * kernel objects, and reference existing ones. */ - error = ipfw_rewrite_rule_uidx(chain, ci); + error = rewrite_rule_uidx(chain, ci); if (error != 0) { /* @@ -2286,7 +2294,7 @@ set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule) * * Used to rollback partially converted rule on error. */ -void +static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib, struct obj_idx *end) { @@ -2406,6 +2414,137 @@ ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti, return (0); } +/* + * Finds and bumps refcount for objects referenced by given @rule. + * Auto-creates non-existing tables. + * Fills in @oib array with userland/kernel indexes. + * + * Returns 0 on success. + */ +static int +ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule, + struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti) +{ + int cmdlen, error, l, numnew; + ipfw_insn *cmd; + struct obj_idx *pidx; + int found, unresolved; + + pidx = oib; + l = rule->cmd_len; + cmd = rule->cmd; + cmdlen = 0; + error = 0; + numnew = 0; + found = 0; + unresolved = 0; + + IPFW_UH_WLOCK(ch); + + /* Increase refcount on each existing referenced table. */ + for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) { + cmdlen = F_LEN(cmd); + + error = ref_opcode_object(ch, cmd, ti, pidx, &found, + &unresolved); + if (error != 0) + break; + if (found || unresolved) { + pidx->off = rule->cmd_len - l; + pidx++; + } + /* + * Compability stuff for old clients: + * prepare to manually create non-existing objects. + */ + if (unresolved) + numnew++; + } + + if (error != 0) { + /* Unref everything we have already done */ + unref_oib_objects(ch, rule->cmd, oib, pidx); + IPFW_UH_WUNLOCK(ch); + return (error); + } + IPFW_UH_WUNLOCK(ch); + + /* Perform auto-creation for non-existing objects */ + if (numnew != 0) + error = create_objects_compat(ch, rule->cmd, oib, pidx, ti); + + /* Calculate real number of dynamic objects */ + ci->object_opcodes = (uint16_t)(pidx - oib); + + return (error); +} + +/* + * Checks is opcode is referencing table of appropriate type. + * Adds reference count for found table if true. + * Rewrites user-supplied opcode values with kernel ones. + * + * Returns 0 on success and appropriate error code otherwise. + */ +static int +rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci) +{ + int error; + ipfw_insn *cmd; + uint8_t type; + struct obj_idx *p, *pidx_first, *pidx_last; + struct tid_info ti; + + /* + * Prepare an array for storing opcode indices. + * Use stack allocation by default. + */ + if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) { + /* Stack */ + pidx_first = ci->obuf; + } else + pidx_first = malloc( + ci->object_opcodes * sizeof(struct obj_idx), + M_IPFW, M_WAITOK | M_ZERO); + + error = 0; + type = 0; + memset(&ti, 0, sizeof(ti)); + + /* + * Use default set for looking up tables (old way) or + * use set rule is assigned to (new way). + */ + ti.set = (V_fw_tables_sets != 0) ? ci->krule->set : 0; + if (ci->ctlv != NULL) { + ti.tlvs = (void *)(ci->ctlv + 1); + ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv); + } + + /* Reference all used tables and other objects */ + error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti); + if (error != 0) + goto free; + /* + * Note that ref_rule_objects() might have updated ci->object_opcodes + * to reflect actual number of object opcodes. + */ + + /* Perform rule rewrite */ + p = pidx_first; + pidx_last = pidx_first + ci->object_opcodes; + for (p = pidx_first; p < pidx_last; p++) { + cmd = ci->krule->cmd + p->off; + update_opcode_kidx(cmd, p->kidx); + } + +free: + if (pidx_first != ci->obuf) + free(pidx_first, M_IPFW); + + return (error); +} + /* * Adds one or more rules to ipfw @chain. * Data layout (version 0)(current): diff --git a/sys/netpfil/ipfw/ip_fw_table.c b/sys/netpfil/ipfw/ip_fw_table.c index a1ee5dd95c57..4af7c88e29d2 100644 --- a/sys/netpfil/ipfw/ip_fw_table.c +++ b/sys/netpfil/ipfw/ip_fw_table.c @@ -3336,136 +3336,6 @@ ipfw_move_tables_sets(struct ip_fw_chain *ch, ipfw_range_tlv *rt, return (bad); } -/* - * Finds and bumps refcount for objects referenced by given @rule. - * Auto-creates non-existing tables. - * Fills in @oib array with userland/kernel indexes. - * - * Returns 0 on success. - */ -static int -ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule, - struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti) -{ - int cmdlen, error, l, numnew; - ipfw_insn *cmd; - struct obj_idx *pidx; - int found, unresolved; - - pidx = oib; - l = rule->cmd_len; - cmd = rule->cmd; - cmdlen = 0; - error = 0; - numnew = 0; - found = 0; - unresolved = 0; - - IPFW_UH_WLOCK(ch); - - /* Increase refcount on each existing referenced table. */ - for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) { - cmdlen = F_LEN(cmd); - - error = ref_opcode_object(ch, cmd, ti, pidx, &found, &unresolved); - if (error != 0) - break; - if (found || unresolved) { - pidx->off = rule->cmd_len - l; - pidx++; - } - /* - * Compability stuff for old clients: - * prepare to manually create non-existing objects. - */ - if (unresolved) - numnew++; - } - - if (error != 0) { - /* Unref everything we have already done */ - unref_oib_objects(ch, rule->cmd, oib, pidx); - IPFW_UH_WUNLOCK(ch); - return (error); - } - IPFW_UH_WUNLOCK(ch); - - /* Perform auto-creation for non-existing objects */ - if (numnew != 0) - error = create_objects_compat(ch, rule->cmd, oib, pidx, ti); - - /* Calculate real number of dynamic objects */ - ci->object_opcodes = (uint16_t)(pidx - oib); - - return (error); -} - -/* - * Checks is opcode is referencing table of appropriate type. - * Adds reference count for found table if true. - * Rewrites user-supplied opcode values with kernel ones. - * - * Returns 0 on success and appropriate error code otherwise. - */ -int -ipfw_rewrite_rule_uidx(struct ip_fw_chain *chain, - struct rule_check_info *ci) -{ - int error; - ipfw_insn *cmd; - uint8_t type; - struct obj_idx *p, *pidx_first, *pidx_last; - struct tid_info ti; - - /* - * Prepare an array for storing opcode indices. - * Use stack allocation by default. - */ - if (ci->object_opcodes <= (sizeof(ci->obuf)/sizeof(ci->obuf[0]))) { - /* Stack */ - pidx_first = ci->obuf; - } else - pidx_first = malloc(ci->object_opcodes * sizeof(struct obj_idx), - M_IPFW, M_WAITOK | M_ZERO); - - error = 0; - type = 0; - memset(&ti, 0, sizeof(ti)); - - /* - * Use default set for looking up tables (old way) or - * use set rule is assigned to (new way). - */ - ti.set = (V_fw_tables_sets != 0) ? ci->krule->set : 0; - if (ci->ctlv != NULL) { - ti.tlvs = (void *)(ci->ctlv + 1); - ti.tlen = ci->ctlv->head.length - sizeof(ipfw_obj_ctlv); - } - - /* Reference all used tables and other objects */ - error = ref_rule_objects(chain, ci->krule, ci, pidx_first, &ti); - if (error != 0) - goto free; - /* - * Note that ref_rule_objects() might have updated ci->object_opcodes - * to reflect actual number of object opcodes. - */ - - /* Perform rule rewrite */ - p = pidx_first; - pidx_last = pidx_first + ci->object_opcodes; - for (p = pidx_first; p < pidx_last; p++) { - cmd = ci->krule->cmd + p->off; - update_opcode_kidx(cmd, p->kidx); - } - -free: - if (pidx_first != ci->obuf) - free(pidx_first, M_IPFW); - - return (error); -} - static struct ipfw_sopt_handler scodes[] = { { IP_FW_TABLE_XCREATE, 0, HDIR_SET, create_table }, { IP_FW_TABLE_XDESTROY, 0, HDIR_SET, flush_table_v0 }, From a561b1060c97af7ef4c95bcdf1ac2182b51c11b3 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 21:04:37 +0000 Subject: [PATCH 053/143] Mark some more .PHONY targets. Sponsored by: EMC / Isilon Storage Division --- Makefile | 4 ++-- Makefile.inc1 | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 2e4e6763d7a8..b9d3ffeda63f 100644 --- a/Makefile +++ b/Makefile @@ -406,7 +406,7 @@ MAKEFAIL=cat universe_prologue: upgrade_checks universe: universe_prologue -universe_prologue: +universe_prologue: .PHONY @echo "--------------------------------------------------------------" @echo ">>> make universe started on ${STARTTIME}" @echo "--------------------------------------------------------------" @@ -492,7 +492,7 @@ universe_kernconf_${TARGET}_${kernel}: .MAKE "check _.${TARGET}.${kernel} for details"| ${MAKEFAIL})) .endfor universe: universe_epilogue -universe_epilogue: +universe_epilogue: .PHONY @echo "--------------------------------------------------------------" @echo ">>> make universe completed on `LC_ALL=C date`" @echo " (started ${STARTTIME})" diff --git a/Makefile.inc1 b/Makefile.inc1 index 27c8808e4499..4c60536dc413 100644 --- a/Makefile.inc1 +++ b/Makefile.inc1 @@ -649,12 +649,12 @@ WMAKE_TGTS+= build${libcompat} buildworld: buildworld_prologue ${WMAKE_TGTS} buildworld_epilogue .ORDER: buildworld_prologue ${WMAKE_TGTS} buildworld_epilogue -buildworld_prologue: +buildworld_prologue: .PHONY @echo "--------------------------------------------------------------" @echo ">>> World build started on `LC_ALL=C date`" @echo "--------------------------------------------------------------" -buildworld_epilogue: +buildworld_epilogue: .PHONY @echo @echo "--------------------------------------------------------------" @echo ">>> World build completed on `LC_ALL=C date`" From 94086cea279d930eb2fbe7d680585abde7e9c095 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 21:04:42 +0000 Subject: [PATCH 054/143] Rework META_TARGETS so that it automatically adds META_DEPS to the targets. This will only be done if the target is defined, so if the target is defined after bsd.sys.mk is included then it needs to manually add ${META_DEPS} still. Sponsored by: EMC / Isilon Storage Division --- include/Makefile | 16 ++++++++-------- share/examples/Makefile | 4 ++-- share/mk/bsd.sys.mk | 7 +++++++ share/mk/local.sys.mk | 4 ++++ share/sendmail/Makefile | 4 ++-- share/zoneinfo/Makefile | 4 ++-- 6 files changed, 25 insertions(+), 14 deletions(-) diff --git a/include/Makefile b/include/Makefile index bb7909884ec9..c949ede9574b 100644 --- a/include/Makefile +++ b/include/Makefile @@ -131,13 +131,8 @@ _MARCHS+= x86 META_TARGETS+= compat copies symlinks stage_includes: ${SHARED} -.include - -installincludes: ${SHARED} -${SHARED}: compat - # Take care of stale directory-level symlinks. -compat: ${META_DEPS} +compat: .for i in ${LDIRS} ${LSUBDIRS} machine ${_MARCHS} crypto if [ -L ${DESTDIR}${INCLUDEDIR}/$i ]; then \ rm -f ${DESTDIR}${INCLUDEDIR}/$i; \ @@ -147,7 +142,7 @@ compat: ${META_DEPS} -f ${.CURDIR}/../etc/mtree/BSD.include.dist \ -p ${DESTDIR}${INCLUDEDIR} > /dev/null -copies: ${META_DEPS} +copies: .for i in ${LDIRS} ${LSUBDIRS} ${LSUBSUBDIRS} crypto machine machine/pc \ ${_MARCHS} if [ -d ${DESTDIR}${INCLUDEDIR}/$i ]; then \ @@ -233,7 +228,7 @@ copies: ${META_DEPS} ${INSTALL} -C -o ${BINOWN} -g ${BINGRP} -m 444 teken.h \ ${DESTDIR}${INCLUDEDIR}/teken -symlinks: ${META_DEPS} +symlinks: @${ECHO} "Setting up symlinks to kernel source tree..." .for i in ${LDIRS} cd ${.CURDIR}/../sys/$i; \ @@ -347,6 +342,11 @@ symlinks: ${META_DEPS} ${DESTDIR}${INCLUDEDIR}/rpc; \ done +.include + +installincludes: ${SHARED} +${SHARED}: compat + .if ${MACHINE} == "host" && !defined(_SKIP_BUILD) # we're here because we are building a sysroot... # we need MACHINE et al set correctly diff --git a/share/examples/Makefile b/share/examples/Makefile index cbc85b067048..ed5c3f345fc9 100644 --- a/share/examples/Makefile +++ b/share/examples/Makefile @@ -222,7 +222,7 @@ beforeinstall: ${SHARED} etc-examples META_TARGETS+= copies symlinks .ORDER: ${SHARED} etc-examples -copies: ${META_DEPS} +copies: .for i in ${LDIRS} if [ -L ${DESTDIR}${BINDIR}/$i ]; then \ rm -f ${DESTDIR}${BINDIR}/$i; \ @@ -235,7 +235,7 @@ copies: ${META_DEPS} ${.CURDIR}/${file} ${DESTDIR}${BINDIR}/${file} .endfor -symlinks: ${META_DEPS} +symlinks: .for i in ${LDIRS} rm -rf ${DESTDIR}${BINDIR}/$i ln -s ${.CURDIR}/$i ${DESTDIR}${BINDIR}/$i diff --git a/share/mk/bsd.sys.mk b/share/mk/bsd.sys.mk index 8471699dbc3e..5660bd43b83f 100644 --- a/share/mk/bsd.sys.mk +++ b/share/mk/bsd.sys.mk @@ -297,3 +297,10 @@ STAGE_SYMLINKS.links= ${SYMLINKS} .endif .endif +.if defined(META_TARGETS) +.for _tgt in ${META_TARGETS} +.if target(${_tgt}) +${_tgt}: ${META_DEPS} +.endif +.endfor +.endif diff --git a/share/mk/local.sys.mk b/share/mk/local.sys.mk index f6a98245a857..68e679f010a7 100644 --- a/share/mk/local.sys.mk +++ b/share/mk/local.sys.mk @@ -32,6 +32,10 @@ OBJTOP?= ${.OBJDIR:S,${.CURDIR},,}${SRCTOP} .if ${.MAKE.MODE:Mmeta*} != "" # we can afford to use cookies to prevent some targets # re-running needlessly but only when using filemon. +# Targets that should support the meta mode cookie handling should just be +# added to META_TARGETS. If bsd.sys.mk cannot be included then ${META_DEPS} +# should be added as a target dependency as well. Otherwise the target +# is added to in bsd.sys.mk since it comes last. .if ${.MAKE.MODE:Mnofilemon} == "" META_COOKIE_COND= empty(.TARGET:M${.OBJDIR}) META_COOKIE= ${COOKIE.${.TARGET}:U${${META_COOKIE_COND}:?${.OBJDIR}/${.TARGET}:${.TARGET}}} diff --git a/share/sendmail/Makefile b/share/sendmail/Makefile index 9ec23f2030dd..84757ddc083f 100644 --- a/share/sendmail/Makefile +++ b/share/sendmail/Makefile @@ -18,7 +18,7 @@ all clean cleandir depend lint tags: beforeinstall: ${SHARED} META_TARGETS+= copies symlinks -copies: ${META_DEPS} +copies: if [ -L ${DDIR}/${CFDIR} ]; then rm -f ${DDIR}/${CFDIR}; fi .for dir in ${CFDIRS} ${INSTALL} -o ${BINOWN} -g ${BINGRP} -m 755 -d ${DDIR}/${dir} @@ -27,7 +27,7 @@ copies: ${META_DEPS} ${INSTALL} -o ${BINOWN} -g ${BINGRP} -m 444 ${SENDMAIL_DIR}/${file} ${DDIR}/${file} .endfor -symlinks: ${META_DEPS} +symlinks: rm -rf ${DDIR}/${CFDIR}; ln -s ${SENDMAIL_DIR}/${CFDIR} ${DDIR}/${CFDIR} .include diff --git a/share/zoneinfo/Makefile b/share/zoneinfo/Makefile index 1ca7ea6cd95d..356d0ad20bda 100644 --- a/share/zoneinfo/Makefile +++ b/share/zoneinfo/Makefile @@ -72,7 +72,7 @@ all: zoneinfo .endif META_TARGETS+= zoneinfo install-zoneinfo -zoneinfo: yearistype ${TDATA} ${META_DEPS} +zoneinfo: yearistype ${TDATA} mkdir -p ${TZBUILDDIR} cd ${TZBUILDDIR}; mkdir -p ${TZBUILDSUBDIRS} umask 022; cd ${.CURDIR}; \ @@ -80,7 +80,7 @@ zoneinfo: yearistype ${TDATA} ${META_DEPS} ${LEAPFILE} -y ${.OBJDIR}/yearistype ${TZFILES} beforeinstall: install-zoneinfo -install-zoneinfo: ${META_DEPS} +install-zoneinfo: cd ${TZBUILDDIR} && \ find -s * -type f -print -exec ${INSTALL} \ -o ${BINOWN} -g ${BINGRP} -m ${NOBINMODE} \ From 2d9796bd246fbfb7ef9bf4222f231ac4ebcfa8ee Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 21:04:45 +0000 Subject: [PATCH 055/143] Follow-up r297835: Let the intented default cookie work. This happened to work for not prepending .OBJDIR twice but broke the other case of prepending it when needed. Pointyhat to: bdrewery Sponsored by: EMC / Isilon Storage Division --- share/mk/local.sys.mk | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/share/mk/local.sys.mk b/share/mk/local.sys.mk index 68e679f010a7..e3d212c6b384 100644 --- a/share/mk/local.sys.mk +++ b/share/mk/local.sys.mk @@ -37,8 +37,11 @@ OBJTOP?= ${.OBJDIR:S,${.CURDIR},,}${SRCTOP} # should be added as a target dependency as well. Otherwise the target # is added to in bsd.sys.mk since it comes last. .if ${.MAKE.MODE:Mnofilemon} == "" -META_COOKIE_COND= empty(.TARGET:M${.OBJDIR}) -META_COOKIE= ${COOKIE.${.TARGET}:U${${META_COOKIE_COND}:?${.OBJDIR}/${.TARGET}:${.TARGET}}} +# Prepend .OBJDIR if not already there. +_META_COOKIE_COND= "${.TARGET:M${.OBJDIR}/*}" == "" +_META_COOKIE_DEFAULT= ${${_META_COOKIE_COND}:?${.OBJDIR}/${.TARGET}:${.TARGET}} +# Use the default if COOKIE.${.TARGET} is not defined. +META_COOKIE= ${COOKIE.${.TARGET}:U${_META_COOKIE_DEFAULT}} META_COOKIE_RM= @rm -f ${META_COOKIE} META_COOKIE_TOUCH= @touch ${META_COOKIE} CLEANFILES+= ${META_TARGETS} From d7296a8faeef2f4a69307412f620504604c76392 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 21:04:49 +0000 Subject: [PATCH 056/143] Implement the dependency condition more safely. Nested : are not handled well without "". Sponsored by: EMC / Isilon Storage Division --- share/mk/bsd.dep.mk | 2 +- sys/conf/kern.post.mk | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/share/mk/bsd.dep.mk b/share/mk/bsd.dep.mk index 50ed33c2838d..d80cb9de117a 100644 --- a/share/mk/bsd.dep.mk +++ b/share/mk/bsd.dep.mk @@ -174,7 +174,7 @@ DEPEND_CFLAGS+= -MT${.TARGET} .if defined(.PARSEDIR) # Only add in DEPEND_CFLAGS for CFLAGS on files we expect from DEPENDOBJS # as those are the only ones we will include. -DEPEND_CFLAGS_CONDITION= !empty(DEPENDOBJS:M${.TARGET:${DEPEND_FILTER}}) +DEPEND_CFLAGS_CONDITION= "${DEPENDOBJS:M${.TARGET:${DEPEND_FILTER}}}" != "" CFLAGS+= ${${DEPEND_CFLAGS_CONDITION}:?${DEPEND_CFLAGS}:} .else CFLAGS+= ${DEPEND_CFLAGS} diff --git a/sys/conf/kern.post.mk b/sys/conf/kern.post.mk index d28e87b6875a..3286c6656fcd 100644 --- a/sys/conf/kern.post.mk +++ b/sys/conf/kern.post.mk @@ -215,7 +215,7 @@ DEPEND_CFLAGS+= -MT${.TARGET} .if defined(.PARSEDIR) # Only add in DEPEND_CFLAGS for CFLAGS on files we expect from DEPENDOBJS # as those are the only ones we will include. -DEPEND_CFLAGS_CONDITION= !empty(DEPENDOBJS:M${.TARGET}) +DEPEND_CFLAGS_CONDITION= "${DEPENDOBJS:M${.TARGET}}" != "" CFLAGS+= ${${DEPEND_CFLAGS_CONDITION}:?${DEPEND_CFLAGS}:} .else CFLAGS+= ${DEPEND_CFLAGS} From d1dd034d078c8ce6c052bada500f90977c535e42 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 21:06:10 +0000 Subject: [PATCH 057/143] META_MODE: Don't rebuild build-tools targets during normal build. This avoids 'build command changed' due to CFLAGS/CC changes during the normal build. Without this the build-tools targets end up rebuilding for the *target* rather than keeping the native versions built in build-tools. Sponsored by: EMC / Isilon Storage Division --- Makefile.inc1 | 4 ++++ Makefile.libcompat | 4 ++++ bin/csh/Makefile | 2 +- bin/sh/Makefile | 6 +++--- lib/libmagic/Makefile | 2 +- lib/ncurses/ncurses/Makefile | 4 ++-- share/syscons/scrnmaps/Makefile | 2 +- usr.bin/awk/Makefile | 2 +- usr.bin/mkcsmapper_static/Makefile | 2 ++ usr.bin/mkesdb_static/Makefile | 2 ++ usr.bin/vi/catalog/Makefile | 2 +- 11 files changed, 22 insertions(+), 10 deletions(-) diff --git a/Makefile.inc1 b/Makefile.inc1 index 4c60536dc413..7d0238f599a8 100644 --- a/Makefile.inc1 +++ b/Makefile.inc1 @@ -296,6 +296,10 @@ CROSSENV+= MAKEOBJDIRPREFIX=${OBJTREE} \ MACHINE_ARCH=${TARGET_ARCH} \ MACHINE=${TARGET} \ CPUTYPE=${TARGET_CPUTYPE} +.if ${MK_META_MODE} != "no" +# Don't rebuild build-tools targets during normal build. +CROSSENV+= BUILD_TOOLS_META=.NOMETA_CMP +.endif .if ${MK_GROFF} != "no" CROSSENV+= GROFF_BIN_PATH=${WORLDTMP}/legacy/usr/bin \ GROFF_FONT_PATH=${WORLDTMP}/legacy/usr/share/groff_font \ diff --git a/Makefile.libcompat b/Makefile.libcompat index 2c15a9bbd3cd..560a50c42573 100644 --- a/Makefile.libcompat +++ b/Makefile.libcompat @@ -88,6 +88,10 @@ LIBCOMPATWMAKEENV+= MAKEOBJDIRPREFIX=${LIBCOMPAT_OBJTREE} \ LIBDIR=/usr/lib${libcompat} \ SHLIBDIR=/usr/lib${libcompat} \ DTRACE="${LIB$COMPATDTRACE:U${DTRACE}}" +.if ${MK_META_MODE} != "no" +# Don't rebuild build-tools targets during normal build. +LIBCOMPATWMAKEENV+= BUILD_TOOLS_META=.NOMETA_CMP +.endif LIBCOMPATWMAKEFLAGS+= CC="${XCC} ${LIBCOMPATCFLAGS}" \ CXX="${XCXX} ${LIBCOMPATCFLAGS} ${LIBCOMPATCXXFLAGS}" \ DESTDIR=${LIBCOMPATTMP} \ diff --git a/bin/csh/Makefile b/bin/csh/Makefile index 2c9ae220db91..f55f24196f30 100644 --- a/bin/csh/Makefile +++ b/bin/csh/Makefile @@ -109,7 +109,7 @@ csh.1: tcsh.man build-tools: gethost -gethost: gethost.c sh.err.h tc.const.h sh.h +gethost: gethost.c sh.err.h tc.const.h sh.h ${BUILD_TOOLS_META} @rm -f ${.TARGET} ${CC} -o gethost ${LDFLAGS} ${CFLAGS:C/-DHAVE_ICONV//} \ ${TCSHDIR}/gethost.c diff --git a/bin/sh/Makefile b/bin/sh/Makefile index 3f28a1231fd3..e6d1d83a887a 100644 --- a/bin/sh/Makefile +++ b/bin/sh/Makefile @@ -44,10 +44,10 @@ builtins.c builtins.h: mkbuiltins builtins.def # XXX this is just to stop the default .c rule being used, so that the # intermediate object has a fixed name. # XXX we have a default .c rule, but no default .o rule. -.o: +mknodes.o mksyntax.o: ${BUILD_TOOLS_META} ${CC} ${CFLAGS} ${LDFLAGS} ${.IMPSRC} ${LDLIBS} -o ${.TARGET} -mknodes: mknodes.o -mksyntax: mksyntax.o +mknodes: mknodes.o ${BUILD_TOOLS_META} +mksyntax: mksyntax.o ${BUILD_TOOLS_META} .ORDER: nodes.c nodes.h nodes.c nodes.h: mknodes nodetypes nodes.c.pat diff --git a/lib/libmagic/Makefile b/lib/libmagic/Makefile index 2add1d3c27b5..6baacc8ac034 100644 --- a/lib/libmagic/Makefile +++ b/lib/libmagic/Makefile @@ -39,7 +39,7 @@ magic.mgc: mkmagic magic CLEANFILES+= mkmagic build-tools: mkmagic -mkmagic: apprentice.c cdf_time.c encoding.c funcs.c magic.c print.c +mkmagic: apprentice.c cdf_time.c encoding.c funcs.c magic.c print.c ${BUILD_TOOLS_META} ${CC} ${CFLAGS} -DCOMPILE_ONLY ${LDFLAGS} -o ${.TARGET} ${.ALLSRC} \ ${LDADD} diff --git a/lib/ncurses/ncurses/Makefile b/lib/ncurses/ncurses/Makefile index fc55bfedb875..f5405e867aee 100644 --- a/lib/ncurses/ncurses/Makefile +++ b/lib/ncurses/ncurses/Makefile @@ -389,10 +389,10 @@ keys.list: MKkeys_list.sh Caps # Build tools build-tools: make_hash make_keys -make_keys: make_keys.c names.c ncurses_def.h ${HEADERS} +make_keys: make_keys.c names.c ncurses_def.h ${HEADERS} ${BUILD_TOOLS_META} ${CC} -o $@ ${CFLAGS} ${NCURSES_DIR}/ncurses/tinfo/make_keys.c -make_hash: make_hash.c hashsize.h ncurses_def.h ${HEADERS} +make_hash: make_hash.c hashsize.h ncurses_def.h ${HEADERS} ${BUILD_TOOLS_META} ${CC} -o $@ ${CFLAGS} -DMAIN_PROGRAM \ ${NCURSES_DIR}/ncurses/tinfo/make_hash.c diff --git a/share/syscons/scrnmaps/Makefile b/share/syscons/scrnmaps/Makefile index 1c5dc88382a1..1e14e5052738 100644 --- a/share/syscons/scrnmaps/Makefile +++ b/share/syscons/scrnmaps/Makefile @@ -19,7 +19,7 @@ ${SCRMAPS}: ${.TARGET:R}.mk uuencode ${.TARGET:R}.tmp ${.TARGET:R} > ${.TARGET} rm -f ${.TARGET:R}.tmp -${SCRMAPS_MK}: ${.TARGET:R} mkscrfil.c +${SCRMAPS_MK}: ${.TARGET:R} mkscrfil.c ${BUILD_TOOLS_META} ${CC} ${CFLAGS} -I${.CURDIR} -DFIL=\"${.TARGET:R}\" ${LDFLAGS} \ -o ${.TARGET} ${.CURDIR}/mkscrfil.c diff --git a/usr.bin/awk/Makefile b/usr.bin/awk/Makefile index 80ca5dbdb9cd..e2e2758131c1 100644 --- a/usr.bin/awk/Makefile +++ b/usr.bin/awk/Makefile @@ -24,6 +24,6 @@ proctab.c: maketab ./maketab > proctab.c build-tools: maketab -maketab: ytab.h ${AWKSRC}/maketab.c +maketab: ytab.h ${AWKSRC}/maketab.c ${BUILD_TOOLS_META} .include diff --git a/usr.bin/mkcsmapper_static/Makefile b/usr.bin/mkcsmapper_static/Makefile index 21014e930b63..a416b20645db 100644 --- a/usr.bin/mkcsmapper_static/Makefile +++ b/usr.bin/mkcsmapper_static/Makefile @@ -13,3 +13,5 @@ build-tools: mkcsmapper_static .include "${.CURDIR}/../mkcsmapper/Makefile.inc" .include + +${PROG}: ${BUILD_TOOLS_META} diff --git a/usr.bin/mkesdb_static/Makefile b/usr.bin/mkesdb_static/Makefile index 2696a23700d5..9ce020920808 100644 --- a/usr.bin/mkesdb_static/Makefile +++ b/usr.bin/mkesdb_static/Makefile @@ -13,3 +13,5 @@ build-tools: mkesdb_static .include "${.CURDIR}/../mkesdb/Makefile.inc" .include + +${PROG}: ${BUILD_TOOLS_META} diff --git a/usr.bin/vi/catalog/Makefile b/usr.bin/vi/catalog/Makefile index e2ca579ba57c..d2c349a13426 100644 --- a/usr.bin/vi/catalog/Makefile +++ b/usr.bin/vi/catalog/Makefile @@ -100,7 +100,7 @@ english.base: dump ${SCAN} #Makefile sort -nu > $@ -dump: dump.c +dump: dump.c ${BUILD_TOOLS_META} ${CC} -o ${.TARGET} ${.ALLSRC} CLEANFILES+= dump ${CAT} english.base *.check __ck1 __ck2 From fdff4951ca6d3c9b9d3e5cc69fc48a3259f8a375 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 21:09:03 +0000 Subject: [PATCH 058/143] META_MODE: Pass along the default sysroot in bootstrap-tools to avoid rebuilds later. Some of the clang libraries build in this phase and the cross-tools phase. Later in the cross-tools phase when they build with a default TOOLS_PREFIX, they see a changed build command in meta mode due to the changed DEFAULT_SYSROOT. This is avoided by passing along TOOLS_PREFIX earlier. Sponsored by: EMC / Isilon Storage Division --- Makefile.inc1 | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile.inc1 b/Makefile.inc1 index 7d0238f599a8..28dc8fbfc4e5 100644 --- a/Makefile.inc1 +++ b/Makefile.inc1 @@ -311,6 +311,7 @@ CROSSENV+= ${TARGET_CFLAGS} # bootstrap-tools stage BMAKEENV= INSTALL="sh ${.CURDIR}/tools/install.sh" \ + TOOLS_PREFIX=${WORLDTMP} \ PATH=${BPATH}:${PATH} \ WORLDTMP=${WORLDTMP} \ MAKEFLAGS="-m ${.CURDIR}/tools/build/mk ${.MAKEFLAGS}" From fbcdfe1d5bd9e8091afdf5445905f503e0e99e56 Mon Sep 17 00:00:00 2001 From: Enji Cooper Date: Thu, 14 Apr 2016 21:10:53 +0000 Subject: [PATCH 059/143] Clean up trailing whitespace in lib/libcam; no functional change MFC after: 3 weeks Sponsored by: EMC / Isilon Storage Division --- lib/libcam/camlib.c | 24 ++++++++++++------------ lib/libcam/camlib.h | 12 ++++++------ 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/lib/libcam/camlib.c b/lib/libcam/camlib.c index b7024a6d6097..8986230ac68a 100644 --- a/lib/libcam/camlib.c +++ b/lib/libcam/camlib.c @@ -102,7 +102,7 @@ cam_freeccb(union ccb *ccb) * /dev/foo0 * foo0 * nfoo0 - * + * * Some peripheral drivers create separate device nodes with 'n' prefix for * non-rewind operations. Currently only sa(4) tape driver has this feature. * We extract pure peripheral name as device name for this special case. @@ -194,7 +194,7 @@ cam_get_device(const char *path, char *dev_name, int devnamelen, int *unit) /* * At this point, if the last character of the string isn't a - * number, we know the user either didn't give us a device number, + * number, we know the user either didn't give us a device number, * or he gave us a device name/number format we don't recognize. */ if (!isdigit(tmpstr[strlen(tmpstr) - 1])) { @@ -275,7 +275,7 @@ cam_open_btl(path_id_t path_id, target_id_t target_id, lun_id_t target_lun, int fd, bufsize; if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) { - snprintf(cam_errbuf, CAM_ERRBUF_SIZE, + snprintf(cam_errbuf, CAM_ERRBUF_SIZE, "%s: couldn't open %s\n%s: %s", func_name, XPT_DEVICE, func_name, strerror(errno)); return(NULL); @@ -292,7 +292,7 @@ cam_open_btl(path_id_t path_id, target_id_t target_id, lun_id_t target_lun, ccb.cdm.match_buf_len = bufsize; ccb.cdm.matches = (struct dev_match_result *)malloc(bufsize); if (ccb.cdm.matches == NULL) { - snprintf(cam_errbuf, CAM_ERRBUF_SIZE, + snprintf(cam_errbuf, CAM_ERRBUF_SIZE, "%s: couldn't malloc match buffer", func_name); close(fd); return(NULL); @@ -305,14 +305,14 @@ cam_open_btl(path_id_t path_id, target_id_t target_id, lun_id_t target_lun, ccb.cdm.patterns = (struct dev_match_pattern *)malloc( sizeof(struct dev_match_pattern)); if (ccb.cdm.patterns == NULL) { - snprintf(cam_errbuf, CAM_ERRBUF_SIZE, + snprintf(cam_errbuf, CAM_ERRBUF_SIZE, "%s: couldn't malloc pattern buffer", func_name); free(ccb.cdm.matches); close(fd); return(NULL); } ccb.cdm.patterns[0].type = DEV_MATCH_PERIPH; - match_pat = &ccb.cdm.patterns[0].pattern.periph_pattern; + match_pat = &ccb.cdm.patterns[0].pattern.periph_pattern; /* * We're looking for the passthrough device associated with this @@ -421,7 +421,7 @@ cam_lookup_pass(const char *dev_name, int unit, int flags, * passthrough device. */ if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) { - snprintf(cam_errbuf, CAM_ERRBUF_SIZE, + snprintf(cam_errbuf, CAM_ERRBUF_SIZE, "%s: couldn't open %s\n%s: %s", func_name, XPT_DEVICE, func_name, strerror(errno)); return(NULL); @@ -435,7 +435,7 @@ cam_lookup_pass(const char *dev_name, int unit, int flags, ccb.cgdl.unit_number = unit; /* - * Attempt to get the passthrough device. This ioctl will fail if + * Attempt to get the passthrough device. This ioctl will fail if * the device name is null, if the device doesn't exist, or if the * passthrough driver isn't in the kernel. */ @@ -512,7 +512,7 @@ cam_real_open_device(const char *path, int flags, struct cam_device *device, } device->fd = -1; malloced_device = 1; - } + } /* * If the user passed in a path, save it for him. @@ -551,7 +551,7 @@ cam_real_open_device(const char *path, int flags, struct cam_device *device, * we don't have to set any fields. */ ccb.ccb_h.func_code = XPT_GDEVLIST; - + /* * We're only doing this to get some information on the device in * question. Otherwise, we'd have to pass in yet another @@ -611,7 +611,7 @@ cam_real_open_device(const char *path, int flags, struct cam_device *device, goto crod_bailout; } device->pd_type = SID_TYPE(&ccb.cgd.inq_data); - bcopy(&ccb.cgd.inq_data, &device->inq_data, + bcopy(&ccb.cgd.inq_data, &device->inq_data, sizeof(struct scsi_inquiry_data)); device->serial_num_len = ccb.cgd.serial_num_len; bcopy(&ccb.cgd.serial_num, &device->serial_num, device->serial_num_len); @@ -719,7 +719,7 @@ cam_device_dup(struct cam_device *device) newdev = malloc(sizeof(struct cam_device)); if (newdev == NULL) { - snprintf(cam_errbuf, CAM_ERRBUF_SIZE, + snprintf(cam_errbuf, CAM_ERRBUF_SIZE, "%s: couldn't malloc CAM device structure", func_name); return(NULL); } diff --git a/lib/libcam/camlib.h b/lib/libcam/camlib.h index e505c77c43af..4fa6a67d8988 100644 --- a/lib/libcam/camlib.h +++ b/lib/libcam/camlib.h @@ -83,7 +83,7 @@ extern char cam_errbuf[]; struct cam_device { char device_path[MAXPATHLEN];/* - * Pathname of the device + * Pathname of the device * given by the user. This * may be null if the * user states the device @@ -98,15 +98,15 @@ struct cam_device { * Unit number given by * the user. */ - char device_name[DEV_IDLEN+1];/* - * Name of the device, - * e.g. 'pass' + char device_name[DEV_IDLEN+1];/* + * Name of the device, + * e.g. 'pass' */ u_int32_t dev_unit_num; /* Unit number of the passthrough * device associated with this * particular device. */ - + char sim_name[SIM_IDLEN+1]; /* Controller name, e.g. 'ahc' */ u_int32_t sim_unit_number; /* Controller unit number */ u_int32_t bus_id; /* Controller bus number */ @@ -142,7 +142,7 @@ int cam_send_ccb(struct cam_device *device, union ccb *ccb); char * cam_path_string(struct cam_device *dev, char *str, int len); struct cam_device * cam_device_dup(struct cam_device *device); -void cam_device_copy(struct cam_device *src, +void cam_device_copy(struct cam_device *src, struct cam_device *dst); int cam_get_device(const char *path, char *dev_name, int devnamelen, int *unit); From b2df1f7ea13a3a39ee0b4340d909b1048640c5aa Mon Sep 17 00:00:00 2001 From: "Andrey V. Elsukov" Date: Thu, 14 Apr 2016 21:31:16 +0000 Subject: [PATCH 060/143] o Teach opcode rewriting framework handle several rewriters for the same opcode. o Reduce number of times classifier callback is called. It is redundant to call it just after find_op_rw(), since the last does call it already and can have all results. o Do immediately opcode rewrite in the ref_opcode_object(). This eliminates additional classifier lookup later on bulk update. For unresolved opcodes the behavior still the same, we save information from classifier callback in the obj_idx array, then perform automatic objects creation, then perform rewriting for opcodes using indeces from created objects. Obtained from: Yandex LLC Sponsored by: Yandex LLC --- sys/netpfil/ipfw/ip_fw_sockopt.c | 193 ++++++++++++++++++------------- 1 file changed, 110 insertions(+), 83 deletions(-) diff --git a/sys/netpfil/ipfw/ip_fw_sockopt.c b/sys/netpfil/ipfw/ip_fw_sockopt.c index 18f2f193dcd8..52784f490cb5 100644 --- a/sys/netpfil/ipfw/ip_fw_sockopt.c +++ b/sys/netpfil/ipfw/ip_fw_sockopt.c @@ -155,13 +155,14 @@ static struct ipfw_sopt_handler scodes[] = { static int set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule); -struct opcode_obj_rewrite *ipfw_find_op_rw(uint16_t opcode); +static struct opcode_obj_rewrite *find_op_rw(ipfw_insn *cmd, + uint16_t *puidx, uint8_t *ptype); static int mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule, uint32_t *bmask); static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule, struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti); static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, - struct tid_info *ti, struct obj_idx *pidx, int *found, int *unresolved); + struct tid_info *ti, struct obj_idx *pidx, int *unresolved); static void unref_rule_objects(struct ip_fw_chain *chain, struct ip_fw *rule); static void unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib, struct obj_idx *end); @@ -2008,11 +2009,10 @@ static int mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule, uint32_t *bmask) { - int cmdlen, l, count; - ipfw_insn *cmd; - uint16_t kidx; struct opcode_obj_rewrite *rw; - int bidx; + ipfw_insn *cmd; + int bidx, cmdlen, l, count; + uint16_t kidx; uint8_t subtype; l = rule->cmd_len; @@ -2022,15 +2022,15 @@ mark_object_kidx(struct ip_fw_chain *ch, struct ip_fw *rule, for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) { cmdlen = F_LEN(cmd); - rw = ipfw_find_op_rw(cmd->opcode); + rw = find_op_rw(cmd, &kidx, &subtype); if (rw == NULL) continue; - if (rw->classifier(cmd, &kidx, &subtype) != 0) - continue; - bidx = kidx / 32; - /* Maintain separate bitmasks for table and non-table objects */ + /* + * Maintain separate bitmasks for table and + * non-table objects. + */ if (rw->etlv != IPFW_TLV_TBL_NAME) bidx += IPFW_TABLES_MAX / 32; @@ -2202,7 +2202,7 @@ create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd, ti->type = p->type; ti->atype = 0; - rw = ipfw_find_op_rw((cmd + p->off)->opcode); + rw = find_op_rw(cmd + p->off, NULL, NULL); KASSERT(rw != NULL, ("Unable to find handler for op %d", (cmd + p->off)->opcode)); @@ -2237,14 +2237,14 @@ create_objects_compat(struct ip_fw_chain *ch, ipfw_insn *cmd, static int set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule) { - int cmdlen, error, l; - ipfw_insn *cmd; - uint16_t kidx, uidx; - struct named_object *no; struct opcode_obj_rewrite *rw; - uint8_t subtype; + struct named_object *no; + ipfw_insn *cmd; char *end; long val; + int cmdlen, error, l; + uint16_t kidx, uidx; + uint8_t subtype; error = 0; @@ -2254,12 +2254,9 @@ set_legacy_obj_kidx(struct ip_fw_chain *ch, struct ip_fw_rule0 *rule) for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) { cmdlen = F_LEN(cmd); - rw = ipfw_find_op_rw(cmd->opcode); - if (rw == NULL) - continue; - /* Check if is index in given opcode */ - if (rw->classifier(cmd, &kidx, &subtype) != 0) + rw = find_op_rw(cmd, &kidx, &subtype); + if (rw == NULL) continue; /* Try to find referenced kernel object */ @@ -2308,7 +2305,7 @@ unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib, if (p->kidx == 0) continue; - rw = ipfw_find_op_rw((cmd + p->off)->opcode); + rw = find_op_rw(cmd + p->off, NULL, NULL); KASSERT(rw != NULL, ("Unable to find handler for op %d", (cmd + p->off)->opcode)); @@ -2326,11 +2323,11 @@ unref_oib_objects(struct ip_fw_chain *ch, ipfw_insn *cmd, struct obj_idx *oib, static void unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule) { - int cmdlen, l; - ipfw_insn *cmd; - struct named_object *no; - uint16_t kidx; struct opcode_obj_rewrite *rw; + struct named_object *no; + ipfw_insn *cmd; + int cmdlen, l; + uint16_t kidx; uint8_t subtype; IPFW_UH_WLOCK_ASSERT(ch); @@ -2341,12 +2338,9 @@ unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule) for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) { cmdlen = F_LEN(cmd); - rw = ipfw_find_op_rw(cmd->opcode); + rw = find_op_rw(cmd, &kidx, &subtype); if (rw == NULL) continue; - if (rw->classifier(cmd, &kidx, &subtype) != 0) - continue; - no = rw->find_bykidx(ch, kidx); KASSERT(no != NULL, ("table id %d not found", kidx)); @@ -2375,24 +2369,17 @@ unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule) */ int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti, - struct obj_idx *pidx, int *found, int *unresolved) + struct obj_idx *pidx, int *unresolved) { struct named_object *no; struct opcode_obj_rewrite *rw; int error; - *found = 0; - *unresolved = 0; - /* Check if this opcode is candidate for rewrite */ - rw = ipfw_find_op_rw(cmd->opcode); + rw = find_op_rw(cmd, &ti->uidx, &ti->type); if (rw == NULL) return (0); - /* Check if we need to rewrite this opcode */ - if (rw->classifier(cmd, &ti->uidx, &ti->type) != 0) - return (0); - /* Need to rewrite. Save necessary fields */ pidx->uidx = ti->uidx; pidx->type = ti->type; @@ -2402,15 +2389,17 @@ ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti, if (error != 0) return (error); if (no == NULL) { + /* + * Report about unresolved object for automaic + * creation. + */ *unresolved = 1; return (0); } - /* Found. bump refcount */ - *found = 1; + /* Found. Bump refcount and update kidx. */ no->refcnt++; - pidx->kidx = no->kidx; - + rw->update(cmd, no->kidx); return (0); } @@ -2425,40 +2414,34 @@ static int ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule, struct rule_check_info *ci, struct obj_idx *oib, struct tid_info *ti) { - int cmdlen, error, l, numnew; - ipfw_insn *cmd; struct obj_idx *pidx; - int found, unresolved; + ipfw_insn *cmd; + int cmdlen, error, l, unresolved; pidx = oib; l = rule->cmd_len; cmd = rule->cmd; cmdlen = 0; error = 0; - numnew = 0; - found = 0; - unresolved = 0; IPFW_UH_WLOCK(ch); /* Increase refcount on each existing referenced table. */ for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) { cmdlen = F_LEN(cmd); + unresolved = 0; - error = ref_opcode_object(ch, cmd, ti, pidx, &found, - &unresolved); + error = ref_opcode_object(ch, cmd, ti, pidx, &unresolved); if (error != 0) break; - if (found || unresolved) { + /* + * Compability stuff for old clients: + * prepare to automaitcally create non-existing objects. + */ + if (unresolved != 0) { pidx->off = rule->cmd_len - l; pidx++; } - /* - * Compability stuff for old clients: - * prepare to manually create non-existing objects. - */ - if (unresolved) - numnew++; } if (error != 0) { @@ -2470,7 +2453,7 @@ ref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule, IPFW_UH_WUNLOCK(ch); /* Perform auto-creation for non-existing objects */ - if (numnew != 0) + if (pidx != oib) error = create_objects_compat(ch, rule->cmd, oib, pidx, ti); /* Calculate real number of dynamic objects */ @@ -2818,36 +2801,74 @@ compare_opcodes(const void *_a, const void *_b) return (0); } +/* + * XXX: Rewrite bsearch() + */ +static int +find_op_rw_range(uint16_t op, struct opcode_obj_rewrite **plo, + struct opcode_obj_rewrite **phi) +{ + struct opcode_obj_rewrite *ctl3_max, *lo, *hi, h, *rw; + + memset(&h, 0, sizeof(h)); + h.opcode = op; + + rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters, + ctl3_rsize, sizeof(h), compare_opcodes); + if (rw == NULL) + return (1); + + /* Find the first element matching the same opcode */ + lo = rw; + for ( ; lo > ctl3_rewriters && (lo - 1)->opcode == op; lo--) + ; + + /* Find the last element matching the same opcode */ + hi = rw; + ctl3_max = ctl3_rewriters + ctl3_rsize; + for ( ; (hi + 1) < ctl3_max && (hi + 1)->opcode == op; hi++) + ; + + *plo = lo; + *phi = hi; + + return (0); +} + /* * Finds opcode object rewriter based on @code. * * Returns pointer to handler or NULL. */ -struct opcode_obj_rewrite * -ipfw_find_op_rw(uint16_t opcode) +static struct opcode_obj_rewrite * +find_op_rw(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype) { - struct opcode_obj_rewrite *rw, h; + struct opcode_obj_rewrite *rw, *lo, *hi; + uint16_t uidx; + uint8_t subtype; - memset(&h, 0, sizeof(h)); - h.opcode = opcode; + if (find_op_rw_range(cmd->opcode, &lo, &hi) != 0) + return (NULL); - rw = (struct opcode_obj_rewrite *)bsearch(&h, ctl3_rewriters, - ctl3_rsize, sizeof(h), compare_opcodes); + for (rw = lo; rw <= hi; rw++) { + if (rw->classifier(cmd, &uidx, &subtype) == 0) { + if (puidx != NULL) + *puidx = uidx; + if (ptype != NULL) + *ptype = subtype; + return (rw); + } + } - return (rw); + return (NULL); } - int classify_opcode_kidx(ipfw_insn *cmd, uint16_t *puidx) { - struct opcode_obj_rewrite *rw; - uint8_t subtype; - rw = ipfw_find_op_rw(cmd->opcode); - if (rw == NULL) + if (find_op_rw(cmd, puidx, NULL) == 0) return (1); - - return (rw->classifier(cmd, puidx, &subtype)); + return (0); } void @@ -2855,7 +2876,7 @@ update_opcode_kidx(ipfw_insn *cmd, uint16_t idx) { struct opcode_obj_rewrite *rw; - rw = ipfw_find_op_rw(cmd->opcode); + rw = find_op_rw(cmd, NULL, NULL); KASSERT(rw != NULL, ("No handler to update opcode %d", cmd->opcode)); rw->update(cmd, idx); } @@ -2923,20 +2944,26 @@ int ipfw_del_obj_rewriter(struct opcode_obj_rewrite *rw, size_t count) { size_t sz; - struct opcode_obj_rewrite *tmp, *h; + struct opcode_obj_rewrite *ctl3_max, *ktmp, *lo, *hi; int i; CTL3_LOCK(); for (i = 0; i < count; i++) { - tmp = &rw[i]; - h = ipfw_find_op_rw(tmp->opcode); - if (h == NULL) + if (find_op_rw_range(rw[i].opcode, &lo, &hi) != 0) continue; - sz = (ctl3_rewriters + ctl3_rsize - (h + 1)) * sizeof(*h); - memmove(h, h + 1, sz); - ctl3_rsize--; + for (ktmp = lo; ktmp <= hi; ktmp++) { + if (ktmp->classifier != rw[i].classifier) + continue; + + ctl3_max = ctl3_rewriters + ctl3_rsize; + sz = (ctl3_max - (ktmp + 1)) * sizeof(*ktmp); + memmove(ktmp, ktmp + 1, sz); + ctl3_rsize--; + break; + } + } if (ctl3_rsize == 0) { From f8e26ca319f89c0962e10cd57940cdeb74c0fc89 Mon Sep 17 00:00:00 2001 From: "Andrey V. Elsukov" Date: Thu, 14 Apr 2016 21:45:18 +0000 Subject: [PATCH 061/143] Adjust some comments and make ref_opcode_object() static. --- sys/netpfil/ipfw/ip_fw_sockopt.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/sys/netpfil/ipfw/ip_fw_sockopt.c b/sys/netpfil/ipfw/ip_fw_sockopt.c index 52784f490cb5..126466155c56 100644 --- a/sys/netpfil/ipfw/ip_fw_sockopt.c +++ b/sys/netpfil/ipfw/ip_fw_sockopt.c @@ -2362,12 +2362,11 @@ unref_rule_objects(struct ip_fw_chain *ch, struct ip_fw *rule) * Find and reference object (if any) stored in instruction @cmd. * * Saves object info in @pidx, sets - * - @found to 1 if object was found and references * - @unresolved to 1 if object should exists but not found * * Returns non-zero value in case of error. */ -int +static int ref_opcode_object(struct ip_fw_chain *ch, ipfw_insn *cmd, struct tid_info *ti, struct obj_idx *pidx, int *unresolved) { @@ -2513,7 +2512,7 @@ rewrite_rule_uidx(struct ip_fw_chain *chain, struct rule_check_info *ci) * to reflect actual number of object opcodes. */ - /* Perform rule rewrite */ + /* Perform rewrite of remaining opcodes */ p = pidx_first; pidx_last = pidx_first + ci->object_opcodes; for (p = pidx_first; p < pidx_last; p++) { @@ -2994,7 +2993,7 @@ export_objhash_ntlv_internal(struct namedobj_instance *ni, /* * Lists all service objects. * Data layout (v0)(current): - * Request: [ ipfw_obj_lheader ] size = ipfw_cfg_lheader.size + * Request: [ ipfw_obj_lheader ] size = ipfw_obj_lheader.size * Reply: [ ipfw_obj_lheader [ ipfw_obj_ntlv x N ] (optional) ] * Returns 0 on success */ From a6e0c5da99c72476e9cab2d6fd0eb72268e56df8 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Thu, 14 Apr 2016 21:47:58 +0000 Subject: [PATCH 062/143] New CAM I/O scheduler for FreeBSD. The default I/O scheduler is the same as before. The common scheduling bits have moved from inline code in each of the CAM periph drivers into a library that implements the default scheduling. In addition, a number of rate-limiting and I/O preference options can be enabled by adding CAM_IOSCHED_NETFLIX to your config file. A number of extra stats are also maintained. CAM_IOSCHED_NETFLIX isn't on by default because it uses a separate BIO_READ and BIO_WRITE queue, so doesn't honor BIO_ORDERED between these two types of operations. We already didn't honor it for BIO_DELETE, and we don't depend on BIO_ORDERED between reads and writes anywhere in the system (it is currently used with BIO_FLUSH in ZFS to make sure some writes are complete before others start and as a poor-man's soft dependency in one place in UFS where we won't be issuing READs until after the operation completes). However, out of an abundance of caution, it isn't enabled by default. Plus, this also brings in NCQ TRIM support for those SSDs that support it. A black list is also provided for known rogues that use NCQ trim as an excuse to corrupt the drive. It was difficult to separate out into a separate commit. This code has run in production at Netflix for over a year now. Sponsored by: Netflix, Inc Differential Revision: https://reviews.freebsd.org/D4609 --- sys/cam/ata/ata_all.h | 1 + sys/cam/ata/ata_da.c | 451 +++++++++++++++++++++++++++++++++-------- sys/cam/cam_ccb.h | 1 + sys/cam/cam_xpt.c | 5 + sys/cam/scsi/scsi_da.c | 311 ++++++++++++++++++++-------- sys/conf/files | 1 + sys/conf/options | 1 + sys/dev/ahci/ahci.c | 5 +- 8 files changed, 605 insertions(+), 171 deletions(-) diff --git a/sys/cam/ata/ata_all.h b/sys/cam/ata/ata_all.h index 433c61c5a6c1..0eda4f4d5051 100644 --- a/sys/cam/ata/ata_all.h +++ b/sys/cam/ata/ata_all.h @@ -46,6 +46,7 @@ struct ata_cmd { #define CAM_ATAIO_CONTROL 0x04 /* Control, not a command */ #define CAM_ATAIO_NEEDRESULT 0x08 /* Request requires result. */ #define CAM_ATAIO_DMA 0x10 /* DMA command */ +#define CAM_ATAIO_AUX_HACK 0x20 /* Kludge to make FPDMA DSM TRIM work */ u_int8_t command; u_int8_t features; diff --git a/sys/cam/ata/ata_da.c b/sys/cam/ata/ata_da.c index 38cf46e8e190..3d3afbd73dd3 100644 --- a/sys/cam/ata/ata_da.c +++ b/sys/cam/ata/ata_da.c @@ -59,6 +59,7 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include #include @@ -68,6 +69,8 @@ __FBSDID("$FreeBSD$"); #define ATA_MAX_28BIT_LBA 268435455UL +extern int iosched_debug; + typedef enum { ADA_STATE_RAHEAD, ADA_STATE_WCACHE, @@ -87,17 +90,21 @@ typedef enum { ADA_FLAG_CAN_CFA = 0x0400, ADA_FLAG_CAN_POWERMGT = 0x0800, ADA_FLAG_CAN_DMA48 = 0x1000, - ADA_FLAG_DIRTY = 0x2000 + ADA_FLAG_DIRTY = 0x2000, + ADA_FLAG_CAN_NCQ_TRIM = 0x4000, /* CAN_TRIM also set */ + ADA_FLAG_PIM_CAN_NCQ_TRIM = 0x8000 } ada_flags; typedef enum { ADA_Q_NONE = 0x00, ADA_Q_4K = 0x01, + ADA_Q_NCQ_TRIM_BROKEN = 0x02, } ada_quirks; #define ADA_Q_BIT_STRING \ "\020" \ - "\0014K" + "\0014K" \ + "\002NCQ_TRIM_BROKEN" typedef enum { ADA_CCB_RAHEAD = 0x01, @@ -112,6 +119,23 @@ typedef enum { #define ccb_state ppriv_field0 #define ccb_bp ppriv_ptr1 +typedef enum { + ADA_DELETE_NONE, + ADA_DELETE_DISABLE, + ADA_DELETE_CFA_ERASE, + ADA_DELETE_DSM_TRIM, + ADA_DELETE_NCQ_DSM_TRIM, + ADA_DELETE_MIN = ADA_DELETE_CFA_ERASE, + ADA_DELETE_MAX = ADA_DELETE_NCQ_DSM_TRIM, +} ada_delete_methods; + +static const char *ada_delete_method_names[] = + { "NONE", "DISABLE", "CFA_ERASE", "DSM_TRIM", "NCQ_DSM_TRIM" }; +#if 0 +static const char *ada_delete_method_desc[] = + { "NONE", "DISABLED", "CFA Erase", "DSM Trim", "DSM Trim via NCQ" }; +#endif + struct disk_params { u_int8_t heads; u_int8_t secs_per_track; @@ -128,18 +152,18 @@ struct trim_request { }; struct ada_softc { - struct bio_queue_head bio_queue; - struct bio_queue_head trim_queue; + struct cam_iosched_softc *cam_iosched; int outstanding_cmds; /* Number of active commands */ int refcount; /* Active xpt_action() calls */ ada_state state; ada_flags flags; ada_quirks quirks; - int sort_io_queue; + ada_delete_methods delete_method; int trim_max_ranges; - int trim_running; int read_ahead; int write_cache; + int unmappedio; + int rotating; #ifdef ADA_TEST_FAILURE int force_read_error; int force_write_error; @@ -153,6 +177,13 @@ struct ada_softc { struct sysctl_oid *sysctl_tree; struct callout sendordered_c; struct trim_request trim_req; +#ifdef CAM_IO_STATS + struct sysctl_ctx_list sysctl_stats_ctx; + struct sysctl_oid *sysctl_stats_tree; + u_int timeouts; + u_int errors; + u_int invalidations; +#endif }; struct ada_quirk_entry { @@ -328,6 +359,38 @@ static struct ada_quirk_entry ada_quirk_table[] = { T_DIRECT, SIP_MEDIA_FIXED, "*", "M4-CT???M4SSD2*", "*" }, /*quirks*/ADA_Q_4K }, + { + /* + * Crucial M500 SSDs EU07 firmware + * NCQ Trim works ? + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "EU07" }, + /*quirks*/0 + }, + { + /* + * Crucial M500 SSDs all other firmware + * NCQ Trim doesn't work + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "*" }, + /*quirks*/ADA_Q_NCQ_TRIM_BROKEN + }, + { + /* + * Crucial M550 SSDs + * NCQ Trim doesn't work, but only on MU01 firmware + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M550*", "MU01" }, + /*quirks*/ADA_Q_NCQ_TRIM_BROKEN + }, + { + /* + * Crucial MX100 SSDs + * NCQ Trim doesn't work, but only on MU01 firmware + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*MX100*", "MU01" }, + /*quirks*/ADA_Q_NCQ_TRIM_BROKEN + }, { /* * Crucial RealSSD C300 SSDs @@ -400,6 +463,30 @@ static struct ada_quirk_entry ada_quirk_table[] = { T_DIRECT, SIP_MEDIA_FIXED, "*", "MARVELL SD88SA02*", "*" }, /*quirks*/ADA_Q_4K }, + { + /* + * Micron M500 SSDs firmware EU07 + * NCQ Trim works? + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "EU07" }, + /*quirks*/0 + }, + { + /* + * Micron M500 SSDs all other firmware + * NCQ Trim doesn't work + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "*" }, + /*quirks*/ADA_Q_NCQ_TRIM_BROKEN + }, + { + /* + * Micron M5[15]0 SSDs + * NCQ Trim doesn't work, but only MU01 firmware + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M5[15]0*", "MU01" }, + /*quirks*/ADA_Q_NCQ_TRIM_BROKEN + }, { /* * OCZ Agility 2 SSDs @@ -451,26 +538,26 @@ static struct ada_quirk_entry ada_quirk_table[] = { /* * Samsung 830 Series SSDs - * 4k optimised + * 4k optimised, NCQ TRIM Broken (normal TRIM is fine) */ { T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD 830 Series*", "*" }, - /*quirks*/ADA_Q_4K + /*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN }, { /* * Samsung 840 SSDs - * 4k optimised + * 4k optimised, NCQ TRIM Broken (normal TRIM is fine) */ { T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 840*", "*" }, - /*quirks*/ADA_Q_4K + /*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN }, { /* * Samsung 850 SSDs - * 4k optimised + * 4k optimised, NCQ TRIM broken (normal TRIM fine) */ { T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 850*", "*" }, - /*quirks*/ADA_Q_4K + /*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN }, { /* @@ -478,7 +565,7 @@ static struct ada_quirk_entry ada_quirk_table[] = * Samsung PM851 Series SSDs (MZ7TE*) * Samsung PM853T Series SSDs (MZ7GE*) * Samsung SM863 Series SSDs (MZ7KM*) - * 4k optimised + * 4k optimised, NCQ Trim believed working */ { T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7*", "*" }, /*quirks*/ADA_Q_4K @@ -566,8 +653,6 @@ static void adaresume(void *arg); softc->read_ahead : ada_read_ahead) #define ADA_WC (softc->write_cache >= 0 ? \ softc->write_cache : ada_write_cache) -#define ADA_SIO (softc->sort_io_queue >= 0 ? \ - softc->sort_io_queue : cam_sort_io_queues) /* * Most platforms map firmware geometry to actual, but some don't. If @@ -624,6 +709,8 @@ static struct periph_driver adadriver = TAILQ_HEAD_INITIALIZER(adadriver.units), /* generation */ 0 }; +static int adadeletemethodsysctl(SYSCTL_HANDLER_ARGS); + PERIPHDRIVER_DECLARE(ada, adadriver); static int @@ -719,11 +806,7 @@ adaschedule(struct cam_periph *periph) if (softc->state != ADA_STATE_NORMAL) return; - /* Check if we have more work to do. */ - if (bioq_first(&softc->bio_queue) || - (!softc->trim_running && bioq_first(&softc->trim_queue))) { - xpt_schedule(periph, CAM_PRIORITY_NORMAL); - } + cam_iosched_schedule(softc->cam_iosched, periph); } /* @@ -756,14 +839,7 @@ adastrategy(struct bio *bp) /* * Place it in the queue of disk activities for this disk */ - if (bp->bio_cmd == BIO_DELETE) { - bioq_disksort(&softc->trim_queue, bp); - } else { - if (ADA_SIO) - bioq_disksort(&softc->bio_queue, bp); - else - bioq_insert_tail(&softc->bio_queue, bp); - } + cam_iosched_queue_work(softc->cam_iosched, bp); /* * Schedule ourselves for performing the work. @@ -844,7 +920,7 @@ adadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t len 0, NULL, 0, - ada_default_timeout*1000); + 5*1000); if (softc->flags & ADA_FLAG_CAN_48BIT) ata_48bit_cmd(&ccb.ataio, ATA_FLUSHCACHE48, 0, 0, 0); @@ -918,14 +994,16 @@ adaoninvalidate(struct cam_periph *periph) * De-register any async callbacks. */ xpt_register_async(0, adaasync, periph, periph->path); +#ifdef CAM_IO_STATS + softc->invalidations++; +#endif /* * Return all queued I/O with ENXIO. * XXX Handle any transactions queued to the card * with XPT_ABORT_CCB. */ - bioq_flush(&softc->bio_queue, NULL, ENXIO); - bioq_flush(&softc->trim_queue, NULL, ENXIO); + cam_iosched_flush(softc->cam_iosched, NULL, ENXIO); disk_gone(softc->disk); } @@ -939,12 +1017,20 @@ adacleanup(struct cam_periph *periph) cam_periph_unlock(periph); + cam_iosched_fini(softc->cam_iosched); + /* * If we can't free the sysctl tree, oh well... */ - if ((softc->flags & ADA_FLAG_SCTX_INIT) != 0 - && sysctl_ctx_free(&softc->sysctl_ctx) != 0) { - xpt_print(periph->path, "can't remove sysctl context\n"); + if ((softc->flags & ADA_FLAG_SCTX_INIT) != 0) { +#ifdef CAM_IO_STATS + if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0) + xpt_print(periph->path, + "can't remove sysctl stats context\n"); +#endif + if (sysctl_ctx_free(&softc->sysctl_ctx) != 0) + xpt_print(periph->path, + "can't remove sysctl context\n"); } disk_destroy(softc->disk); @@ -953,6 +1039,20 @@ adacleanup(struct cam_periph *periph) cam_periph_lock(periph); } +static void +adasetdeletemethod(struct ada_softc *softc) +{ + + if (softc->flags & ADA_FLAG_CAN_NCQ_TRIM) + softc->delete_method = ADA_DELETE_NCQ_DSM_TRIM; + else if (softc->flags & ADA_FLAG_CAN_TRIM) + softc->delete_method = ADA_DELETE_DSM_TRIM; + else if ((softc->flags & ADA_FLAG_CAN_CFA) && !(softc->flags & ADA_FLAG_CAN_48BIT)) + softc->delete_method = ADA_DELETE_CFA_ERASE; + else + softc->delete_method = ADA_DELETE_NONE; +} + static void adaasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg) @@ -1018,11 +1118,26 @@ adaasync(void *callback_arg, u_int32_t code, softc->flags |= ADA_FLAG_CAN_NCQ; else softc->flags &= ~ADA_FLAG_CAN_NCQ; + if ((cgd.ident_data.support_dsm & ATA_SUPPORT_DSM_TRIM) && - (cgd.inq_flags & SID_DMA)) + (cgd.inq_flags & SID_DMA)) { softc->flags |= ADA_FLAG_CAN_TRIM; - else - softc->flags &= ~ADA_FLAG_CAN_TRIM; + /* + * If we can do RCVSND_FPDMA_QUEUED commands, we may be able to do + * NCQ trims, if we support trims at all. We also need support from + * the sim do do things properly. Perhaps we should look at log 13 + * dword 0 bit 0 and dword 1 bit 0 are set too... + */ + if ((softc->quirks & ADA_Q_NCQ_TRIM_BROKEN) == 0 && + (softc->flags & ADA_FLAG_PIM_CAN_NCQ_TRIM) != 0 && + (cgd.ident_data.satacapabilities2 & ATA_SUPPORT_RCVSND_FPDMA_QUEUED) != 0 && + (softc->flags & ADA_FLAG_CAN_TRIM) != 0) + softc->flags |= ADA_FLAG_CAN_NCQ_TRIM; + else + softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM; + } else + softc->flags &= ~(ADA_FLAG_CAN_TRIM | ADA_FLAG_CAN_NCQ_TRIM); + adasetdeletemethod(softc); cam_periph_async(periph, code, path, arg); break; @@ -1100,6 +1215,10 @@ adasysctlinit(void *context, int pending) return; } + SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree), + OID_AUTO, "delete_method", CTLTYPE_STRING | CTLFLAG_RW, + softc, 0, adadeletemethodsysctl, "A", + "BIO_DELETE execution method"); SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "read_ahead", CTLFLAG_RW | CTLFLAG_MPSAFE, &softc->read_ahead, 0, "Enable disk read ahead."); @@ -1107,9 +1226,11 @@ adasysctlinit(void *context, int pending) OID_AUTO, "write_cache", CTLFLAG_RW | CTLFLAG_MPSAFE, &softc->write_cache, 0, "Enable disk write cache."); SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree), - OID_AUTO, "sort_io_queue", CTLFLAG_RW | CTLFLAG_MPSAFE, - &softc->sort_io_queue, 0, - "Sort IO queue to try and optimise disk access patterns"); + OID_AUTO, "unmapped_io", CTLFLAG_RD | CTLFLAG_MPSAFE, + &softc->unmappedio, 0, "Unmapped I/O leaf"); + SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree), + OID_AUTO, "rotating", CTLFLAG_RD | CTLFLAG_MPSAFE, + &softc->rotating, 0, "Rotating media"); #ifdef ADA_TEST_FAILURE /* * Add a 'door bell' sysctl which allows one to set it from userland @@ -1129,6 +1250,31 @@ adasysctlinit(void *context, int pending) &softc->periodic_read_error, 0, "Force a read error every N reads (don't set too low)."); #endif + +#ifdef CAM_IO_STATS + softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx, + SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats", + CTLFLAG_RD, 0, "Statistics"); + SYSCTL_ADD_INT(&softc->sysctl_stats_ctx, + SYSCTL_CHILDREN(softc->sysctl_stats_tree), + OID_AUTO, "timeouts", CTLFLAG_RD | CTLFLAG_MPSAFE, + &softc->timeouts, 0, + "Device timeouts reported by the SIM"); + SYSCTL_ADD_INT(&softc->sysctl_stats_ctx, + SYSCTL_CHILDREN(softc->sysctl_stats_tree), + OID_AUTO, "errors", CTLFLAG_RD | CTLFLAG_MPSAFE, + &softc->errors, 0, + "Transport errors reported by the SIM."); + SYSCTL_ADD_INT(&softc->sysctl_stats_ctx, + SYSCTL_CHILDREN(softc->sysctl_stats_tree), + OID_AUTO, "pack_invalidations", CTLFLAG_RD | CTLFLAG_MPSAFE, + &softc->invalidations, 0, + "Device pack invalidations."); +#endif + + cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx, + softc->sysctl_tree); + cam_periph_release(periph); } @@ -1148,6 +1294,43 @@ adagetattr(struct bio *bp) return ret; } +static int +adadeletemethodsysctl(SYSCTL_HANDLER_ARGS) +{ + char buf[16]; + const char *p; + struct ada_softc *softc; + int i, error, value, methods; + + softc = (struct ada_softc *)arg1; + + value = softc->delete_method; + if (value < 0 || value > ADA_DELETE_MAX) + p = "UNKNOWN"; + else + p = ada_delete_method_names[value]; + strncpy(buf, p, sizeof(buf)); + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error != 0 || req->newptr == NULL) + return (error); + methods = 1 << ADA_DELETE_DISABLE; + if ((softc->flags & ADA_FLAG_CAN_CFA) && + !(softc->flags & ADA_FLAG_CAN_48BIT)) + methods |= 1 << ADA_DELETE_CFA_ERASE; + if (softc->flags & ADA_FLAG_CAN_TRIM) + methods |= 1 << ADA_DELETE_DSM_TRIM; + if (softc->flags & ADA_FLAG_CAN_NCQ_TRIM) + methods |= 1 << ADA_DELETE_NCQ_DSM_TRIM; + for (i = 0; i <= ADA_DELETE_MAX; i++) { + if (!(methods & (1 << i)) || + strcmp(buf, ada_delete_method_names[i]) != 0) + continue; + softc->delete_method = i; + return (0); + } + return (EINVAL); +} + static cam_status adaregister(struct cam_periph *periph, void *arg) { @@ -1175,8 +1358,11 @@ adaregister(struct cam_periph *periph, void *arg) return(CAM_REQ_CMP_ERR); } - bioq_init(&softc->bio_queue); - bioq_init(&softc->trim_queue); + if (cam_iosched_init(&softc->cam_iosched, periph) != 0) { + printf("adaregister: Unable to probe new device. " + "Unable to allocate iosched memory\n"); + return(CAM_REQ_CMP_ERR); + } if ((cgd->ident_data.capabilities1 & ATA_SUPPORT_DMA) && (cgd->inq_flags & SID_DMA)) @@ -1206,6 +1392,8 @@ adaregister(struct cam_periph *periph, void *arg) if (cgd->ident_data.support.command2 & ATA_SUPPORT_CFA) softc->flags |= ADA_FLAG_CAN_CFA; + adasetdeletemethod(softc); + periph->softc = softc; /* @@ -1246,10 +1434,12 @@ adaregister(struct cam_periph *periph, void *arg) "kern.cam.ada.%d.write_cache", periph->unit_number); TUNABLE_INT_FETCH(announce_buf, &softc->write_cache); /* Disable queue sorting for non-rotational media by default. */ - if (cgd->ident_data.media_rotation_rate == ATA_RATE_NON_ROTATING) - softc->sort_io_queue = 0; - else - softc->sort_io_queue = -1; + if (cgd->ident_data.media_rotation_rate == ATA_RATE_NON_ROTATING) { + softc->rotating = 0; + } else { + softc->rotating = 1; + } + cam_iosched_set_sort_queue(softc->cam_iosched, softc->rotating ? -1 : 0); adagetparams(periph, cgd); softc->disk = disk_alloc(); softc->disk->d_rotation_rate = cgd->ident_data.media_rotation_rate; @@ -1292,8 +1482,23 @@ adaregister(struct cam_periph *periph, void *arg) softc->disk->d_delmaxsize = 256 * softc->params.secsize; } else softc->disk->d_delmaxsize = maxio; - if ((cpi.hba_misc & PIM_UNMAPPED) != 0) + if ((cpi.hba_misc & PIM_UNMAPPED) != 0) { softc->disk->d_flags |= DISKFLAG_UNMAPPED_BIO; + softc->unmappedio = 1; + } + /* + * If we can do RCVSND_FPDMA_QUEUED commands, we may be able to do + * NCQ trims, if we support trims at all. We also need support from + * the sim do do things properly. Perhaps we should look at log 13 + * dword 0 bit 0 and dword 1 bit 0 are set too... + */ + if (cpi.hba_misc & PIM_NCQ_KLUDGE) + softc->flags |= ADA_FLAG_PIM_CAN_NCQ_TRIM; + if ((softc->quirks & ADA_Q_NCQ_TRIM_BROKEN) == 0 && + (softc->flags & ADA_FLAG_PIM_CAN_NCQ_TRIM) != 0 && + (cgd->ident_data.satacapabilities2 & ATA_SUPPORT_RCVSND_FPDMA_QUEUED) != 0 && + (softc->flags & ADA_FLAG_CAN_TRIM) != 0) + softc->flags |= ADA_FLAG_CAN_NCQ_TRIM; strlcpy(softc->disk->d_descr, cgd->ident_data.model, MIN(sizeof(softc->disk->d_descr), sizeof(cgd->ident_data.model))); strlcpy(softc->disk->d_ident, cgd->ident_data.serial, @@ -1320,6 +1525,7 @@ adaregister(struct cam_periph *periph, void *arg) softc->disk->d_fwsectors = softc->params.secs_per_track; softc->disk->d_fwheads = softc->params.heads; ata_disk_firmware_geom_adjust(softc->disk); + adasetdeletemethod(softc); /* * Acquire a reference to the periph before we register with GEOM. @@ -1389,10 +1595,9 @@ adaregister(struct cam_periph *periph, void *arg) return(CAM_REQ_CMP); } -static void -ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio) +static int +ada_dsmtrim_req_create(struct ada_softc *softc, struct bio *bp, struct trim_request *req) { - struct trim_request *req = &softc->trim_req; uint64_t lastlba = (uint64_t)-1; int c, lastcount = 0, off, ranges = 0; @@ -1402,8 +1607,6 @@ ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio) uint64_t lba = bp->bio_pblkno; int count = bp->bio_bcount / softc->params.secsize; - bioq_remove(&softc->trim_queue, bp); - /* Try to extend the previous range. */ if (lba == lastlba) { c = min(count, ATA_DSM_RANGE_MAX - lastcount); @@ -1439,12 +1642,27 @@ ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio) } lastlba = lba; TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue); - bp = bioq_first(&softc->trim_queue); - if (bp == NULL || - bp->bio_bcount / softc->params.secsize > - (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) + + bp = cam_iosched_next_trim(softc->cam_iosched); + if (bp == NULL) break; + if (bp->bio_bcount / softc->params.secsize > + (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) { + cam_iosched_put_back_trim(softc->cam_iosched, bp); + break; + } } while (1); + + return (ranges); +} + +static void +ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio) +{ + struct trim_request *req = &softc->trim_req; + int ranges; + + ranges = ada_dsmtrim_req_create(softc, bp, req); cam_fill_ataio(ataio, ada_retry_count, adadone, @@ -1459,6 +1677,30 @@ ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio) 1) / ATA_DSM_BLK_RANGES); } +static void +ada_ncq_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio) +{ + struct trim_request *req = &softc->trim_req; + int ranges; + + ranges = ada_dsmtrim_req_create(softc, bp, req); + cam_fill_ataio(ataio, + ada_retry_count, + adadone, + CAM_DIR_OUT, + 0, + req->data, + ((ranges + ATA_DSM_BLK_RANGES - 1) / + ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE, + ada_default_timeout * 1000); + ata_ncq_cmd(ataio, + ATA_SEND_FPDMA_QUEUED, + 0, + (ranges + ATA_DSM_BLK_RANGES - 1) / ATA_DSM_BLK_RANGES); + ataio->cmd.sector_count_exp = ATA_SFPDMA_DSM; + ataio->cmd.flags |= CAM_ATAIO_AUX_HACK; +} + static void ada_cfaerase(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio) { @@ -1468,7 +1710,6 @@ ada_cfaerase(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio) bzero(req, sizeof(*req)); TAILQ_INIT(&req->bps); - bioq_remove(&softc->trim_queue, bp); TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue); cam_fill_ataio(ataio, @@ -1499,37 +1740,14 @@ adastart(struct cam_periph *periph, union ccb *start_ccb) struct bio *bp; u_int8_t tag_code; - /* Run TRIM if not running yet. */ - if (!softc->trim_running && - (bp = bioq_first(&softc->trim_queue)) != 0) { - if (softc->flags & ADA_FLAG_CAN_TRIM) { - ada_dsmtrim(softc, bp, ataio); - } else if ((softc->flags & ADA_FLAG_CAN_CFA) && - !(softc->flags & ADA_FLAG_CAN_48BIT)) { - ada_cfaerase(softc, bp, ataio); - } else { - /* This can happen if DMA was disabled. */ - bioq_remove(&softc->trim_queue, bp); - biofinish(bp, NULL, EOPNOTSUPP); - xpt_release_ccb(start_ccb); - adaschedule(periph); - return; - } - softc->trim_running = 1; - start_ccb->ccb_h.ccb_state = ADA_CCB_TRIM; - start_ccb->ccb_h.flags |= CAM_UNLOCKED; - goto out; - } - /* Run regular command. */ - bp = bioq_first(&softc->bio_queue); + bp = cam_iosched_next_bio(softc->cam_iosched); if (bp == NULL) { xpt_release_ccb(start_ccb); break; } - bioq_remove(&softc->bio_queue, bp); - if ((bp->bio_flags & BIO_ORDERED) != 0 - || (softc->flags & ADA_FLAG_NEED_OTAG) != 0) { + if ((bp->bio_flags & BIO_ORDERED) != 0 || + (bp->bio_cmd != BIO_DELETE && (softc->flags & ADA_FLAG_NEED_OTAG) != 0)) { softc->flags &= ~ADA_FLAG_NEED_OTAG; softc->flags |= ADA_FLAG_WAS_OTAG; tag_code = 0; @@ -1659,6 +1877,27 @@ adastart(struct cam_periph *periph, union ccb *start_ccb) } break; } + case BIO_DELETE: + switch (softc->delete_method) { + case ADA_DELETE_NCQ_DSM_TRIM: + ada_ncq_dsmtrim(softc, bp, ataio); + break; + case ADA_DELETE_DSM_TRIM: + ada_dsmtrim(softc, bp, ataio); + break; + case ADA_DELETE_CFA_ERASE: + ada_cfaerase(softc, bp, ataio); + break; + default: + biofinish(bp, NULL, EOPNOTSUPP); + xpt_release_ccb(start_ccb); + adaschedule(periph); + return; + } + start_ccb->ccb_h.ccb_state = ADA_CCB_TRIM; + start_ccb->ccb_h.flags |= CAM_UNLOCKED; + cam_iosched_submit_trim(softc->cam_iosched); + goto out; case BIO_FLUSH: cam_fill_ataio(ataio, 1, @@ -1742,6 +1981,7 @@ adadone(struct cam_periph *periph, union ccb *done_ccb) int error; cam_periph_lock(periph); + bp = (struct bio *)done_ccb->ccb_h.ccb_bp; if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) { error = adaerror(done_ccb, 0, 0); if (error == ERESTART) { @@ -1755,12 +1995,25 @@ adadone(struct cam_periph *periph, union ccb *done_ccb) /*reduction*/0, /*timeout*/0, /*getcount_only*/0); + /* + * If we get an error on an NCQ DSM TRIM, fall back + * to a non-NCQ DSM TRIM forever. Please note that if + * CAN_NCQ_TRIM is set, CAN_TRIM is necessarily set too. + * However, for this one trim, we treat it as advisory + * and return success up the stack. + */ + if (state == ADA_CCB_TRIM && + error != 0 && + (softc->flags & ADA_FLAG_CAN_NCQ_TRIM) != 0) { + softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM; + error = 0; + adasetdeletemethod(softc); + } } else { if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) panic("REQ_CMP with QFRZN"); error = 0; } - bp = (struct bio *)done_ccb->ccb_h.ccb_bp; bp->bio_error = error; if (error != 0) { bp->bio_resid = bp->bio_bcount; @@ -1776,6 +2029,8 @@ adadone(struct cam_periph *periph, union ccb *done_ccb) softc->outstanding_cmds--; if (softc->outstanding_cmds == 0) softc->flags |= ADA_FLAG_WAS_OTAG; + + cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb); xpt_release_ccb(done_ccb); if (state == ADA_CCB_TRIM) { TAILQ_HEAD(, bio) queue; @@ -1793,7 +2048,7 @@ adadone(struct cam_periph *periph, union ccb *done_ccb) * daschedule again so that we don't stall if there are * no other I/Os pending apart from BIO_DELETEs. */ - softc->trim_running = 0; + cam_iosched_trim_done(softc->cam_iosched); adaschedule(periph); cam_periph_unlock(periph); while ((bp1 = TAILQ_FIRST(&queue)) != NULL) { @@ -1807,6 +2062,7 @@ adadone(struct cam_periph *periph, union ccb *done_ccb) biodone(bp1); } } else { + adaschedule(periph); cam_periph_unlock(periph); biodone(bp); } @@ -1898,6 +2154,31 @@ adadone(struct cam_periph *periph, union ccb *done_ccb) static int adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags) { + struct ada_softc *softc; + struct cam_periph *periph; + + periph = xpt_path_periph(ccb->ccb_h.path); + softc = (struct ada_softc *)periph->softc; + + switch (ccb->ccb_h.status & CAM_STATUS_MASK) { + case CAM_CMD_TIMEOUT: +#ifdef CAM_IO_STATS + softc->timeouts++; +#endif + break; + case CAM_REQ_ABORTED: + case CAM_REQ_CMP_ERR: + case CAM_REQ_TERMIO: + case CAM_UNREC_HBA_ERROR: + case CAM_DATA_RUN_ERR: + case CAM_ATA_STATUS_ERROR: +#ifdef CAM_IO_STATS + softc->errors++; +#endif + break; + default: + break; + } return(cam_periph_error(ccb, cam_flags, sense_flags, NULL)); } diff --git a/sys/cam/cam_ccb.h b/sys/cam/cam_ccb.h index 28415edb10b7..c739aa60ddcc 100644 --- a/sys/cam/cam_ccb.h +++ b/sys/cam/cam_ccb.h @@ -581,6 +581,7 @@ typedef enum { } pi_tmflag; typedef enum { + PIM_NCQ_KLUDGE = 0x200, /* Supports the sata ncq trim kludge */ PIM_EXTLUNS = 0x100,/* 64bit extended LUNs supported */ PIM_SCANHILO = 0x80, /* Bus scans from high ID to low ID */ PIM_NOREMOVE = 0x40, /* Removeable devices not included in scan */ diff --git a/sys/cam/cam_xpt.c b/sys/cam/cam_xpt.c index e811fe6e305b..b42685714c87 100644 --- a/sys/cam/cam_xpt.c +++ b/sys/cam/cam_xpt.c @@ -3311,6 +3311,7 @@ xpt_run_devq(struct cam_devq *devq) lock = (mtx_owned(sim->mtx) == 0); if (lock) CAM_SIM_LOCK(sim); + work_ccb->ccb_h.qos.sim_data = sbinuptime(); // xxx uintprt_t too small 32bit platforms (*(sim->sim_action))(sim, work_ccb); if (lock) CAM_SIM_UNLOCK(sim); @@ -4439,6 +4440,8 @@ xpt_done(union ccb *done_ccb) if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0) return; + /* Store the time the ccb was in the sim */ + done_ccb->ccb_h.qos.sim_data = sbinuptime() - done_ccb->ccb_h.qos.sim_data; hash = (done_ccb->ccb_h.path_id + done_ccb->ccb_h.target_id + done_ccb->ccb_h.target_lun) % cam_num_doneqs; queue = &cam_doneqs[hash]; @@ -4459,6 +4462,8 @@ xpt_done_direct(union ccb *done_ccb) if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0) return; + /* Store the time the ccb was in the sim */ + done_ccb->ccb_h.qos.sim_data = sbinuptime() - done_ccb->ccb_h.qos.sim_data; xpt_done_process(&done_ccb->ccb_h); } diff --git a/sys/cam/scsi/scsi_da.c b/sys/cam/scsi/scsi_da.c index 07a6435537ba..907203a24f15 100644 --- a/sys/cam/scsi/scsi_da.c +++ b/sys/cam/scsi/scsi_da.c @@ -60,6 +60,7 @@ __FBSDID("$FreeBSD$"); #include #include #include +#include #include @@ -199,21 +200,19 @@ struct disk_params { #define ATA_TRIM_MAX_RANGES ((UNMAP_BUF_SIZE / \ (ATA_DSM_RANGE_SIZE * ATA_DSM_BLK_SIZE)) * ATA_DSM_BLK_SIZE) +#define DA_WORK_TUR (1 << 16) + struct da_softc { - struct bio_queue_head bio_queue; - struct bio_queue_head delete_queue; + struct cam_iosched_softc *cam_iosched; struct bio_queue_head delete_run_queue; LIST_HEAD(, ccb_hdr) pending_ccbs; - int tur; /* TEST UNIT READY should be sent */ int refcount; /* Active xpt_action() calls */ da_state state; da_flags flags; da_quirks quirks; - int sort_io_queue; int minimum_cmd_size; int error_inject; int trim_max_ranges; - int delete_running; int delete_available; /* Delete methods possibly available */ u_int maxio; uint32_t unmap_max_ranges; @@ -222,6 +221,8 @@ struct da_softc { da_delete_methods delete_method_pref; da_delete_methods delete_method; da_delete_func_t *delete_func; + int unmappedio; + int rotating; struct disk_params params; struct disk *disk; union ccb saved_ccb; @@ -233,6 +234,13 @@ struct da_softc { uint8_t unmap_buf[UNMAP_BUF_SIZE]; struct scsi_read_capacity_data_long rcaplong; struct callout mediapoll_c; +#ifdef CAM_IO_STATS + struct sysctl_ctx_list sysctl_stats_ctx; + struct sysctl_oid *sysctl_stats_tree; + u_int errors; + u_int timeouts; + u_int invalidations; +#endif }; #define dadeleteflag(softc, delete_method, enable) \ @@ -1193,6 +1201,7 @@ static periph_init_t dainit; static void daasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg); static void dasysctlinit(void *context, int pending); +static int dasysctlsofttimeout(SYSCTL_HANDLER_ARGS); static int dacmdsizesysctl(SYSCTL_HANDLER_ARGS); static int dadeletemethodsysctl(SYSCTL_HANDLER_ARGS); static int dadeletemaxsysctl(SYSCTL_HANDLER_ARGS); @@ -1230,6 +1239,10 @@ static timeout_t damediapoll; #define DA_DEFAULT_TIMEOUT 60 /* Timeout in seconds */ #endif +#ifndef DA_DEFAULT_SOFTTIMEOUT +#define DA_DEFAULT_SOFTTIMEOUT 0 +#endif + #ifndef DA_DEFAULT_RETRY #define DA_DEFAULT_RETRY 4 #endif @@ -1238,12 +1251,10 @@ static timeout_t damediapoll; #define DA_DEFAULT_SEND_ORDERED 1 #endif -#define DA_SIO (softc->sort_io_queue >= 0 ? \ - softc->sort_io_queue : cam_sort_io_queues) - static int da_poll_period = DA_DEFAULT_POLL_PERIOD; static int da_retry_count = DA_DEFAULT_RETRY; static int da_default_timeout = DA_DEFAULT_TIMEOUT; +static sbintime_t da_default_softtimeout = DA_DEFAULT_SOFTTIMEOUT; static int da_send_ordered = DA_DEFAULT_SEND_ORDERED; static SYSCTL_NODE(_kern_cam, OID_AUTO, da, CTLFLAG_RD, 0, @@ -1257,6 +1268,11 @@ SYSCTL_INT(_kern_cam_da, OID_AUTO, default_timeout, CTLFLAG_RWTUN, SYSCTL_INT(_kern_cam_da, OID_AUTO, send_ordered, CTLFLAG_RWTUN, &da_send_ordered, 0, "Send Ordered Tags"); +SYSCTL_PROC(_kern_cam_da, OID_AUTO, default_softtimeout, + CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, dasysctlsofttimeout, "I", + "Soft I/O timeout (ms)"); +TUNABLE_LONG("kern.cam.da.default_softtimeout", &da_default_softtimeout); + /* * DA_ORDEREDTAG_INTERVAL determines how often, relative * to the default timeout, we check to see whether an ordered @@ -1400,12 +1416,7 @@ daschedule(struct cam_periph *periph) if (softc->state != DA_STATE_NORMAL) return; - /* Check if we have more work to do. */ - if (bioq_first(&softc->bio_queue) || - (!softc->delete_running && bioq_first(&softc->delete_queue)) || - softc->tur) { - xpt_schedule(periph, CAM_PRIORITY_NORMAL); - } + cam_iosched_schedule(softc->cam_iosched, periph); } /* @@ -1438,13 +1449,7 @@ dastrategy(struct bio *bp) /* * Place it in the queue of disk activities for this disk */ - if (bp->bio_cmd == BIO_DELETE) { - bioq_disksort(&softc->delete_queue, bp); - } else if (DA_SIO) { - bioq_disksort(&softc->bio_queue, bp); - } else { - bioq_insert_tail(&softc->bio_queue, bp); - } + cam_iosched_queue_work(softc->cam_iosched, bp); /* * Schedule ourselves for performing the work. @@ -1519,7 +1524,7 @@ dadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t leng /*begin_lba*/0,/* Cover the whole disk */ /*lb_count*/0, SSD_FULL_SIZE, - 5 * 60 * 1000); + 5 * 1000); xpt_polled_action((union ccb *)&csio); error = cam_periph_error((union ccb *)&csio, @@ -1599,14 +1604,16 @@ daoninvalidate(struct cam_periph *periph) xpt_register_async(0, daasync, periph, periph->path); softc->flags |= DA_FLAG_PACK_INVALID; +#ifdef CAM_IO_STATS + softc->invalidations++; +#endif /* * Return all queued I/O with ENXIO. * XXX Handle any transactions queued to the card * with XPT_ABORT_CCB. */ - bioq_flush(&softc->bio_queue, NULL, ENXIO); - bioq_flush(&softc->delete_queue, NULL, ENXIO); + cam_iosched_flush(softc->cam_iosched, NULL, ENXIO); /* * Tell GEOM that we've gone away, we'll get a callback when it is @@ -1624,12 +1631,20 @@ dacleanup(struct cam_periph *periph) cam_periph_unlock(periph); + cam_iosched_fini(softc->cam_iosched); + /* * If we can't free the sysctl tree, oh well... */ - if ((softc->flags & DA_FLAG_SCTX_INIT) != 0 - && sysctl_ctx_free(&softc->sysctl_ctx) != 0) { - xpt_print(periph->path, "can't remove sysctl context\n"); + if ((softc->flags & DA_FLAG_SCTX_INIT) != 0) { +#ifdef CAM_IO_STATS + if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0) + xpt_print(periph->path, + "can't remove sysctl stats context\n"); +#endif + if (sysctl_ctx_free(&softc->sysctl_ctx) != 0) + xpt_print(periph->path, + "can't remove sysctl context\n"); } callout_drain(&softc->mediapoll_c); @@ -1732,9 +1747,9 @@ daasync(void *callback_arg, u_int32_t code, } case AC_SCSI_AEN: softc = (struct da_softc *)periph->softc; - if (!softc->tur) { + if (!cam_iosched_has_work_flags(softc->cam_iosched, DA_WORK_TUR)) { if (cam_periph_acquire(periph) == CAM_REQ_CMP) { - softc->tur = 1; + cam_iosched_set_work_flags(softc->cam_iosched, DA_WORK_TUR); daschedule(periph); } } @@ -1808,9 +1823,6 @@ dasysctlinit(void *context, int pending) OID_AUTO, "minimum_cmd_size", CTLTYPE_INT | CTLFLAG_RW, &softc->minimum_cmd_size, 0, dacmdsizesysctl, "I", "Minimum CDB size"); - SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree), - OID_AUTO, "sort_io_queue", CTLFLAG_RW, &softc->sort_io_queue, 0, - "Sort IO queue to try and optimise disk access patterns"); SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree), @@ -1821,6 +1833,23 @@ dasysctlinit(void *context, int pending) 0, "error_inject leaf"); + SYSCTL_ADD_INT(&softc->sysctl_ctx, + SYSCTL_CHILDREN(softc->sysctl_tree), + OID_AUTO, + "unmapped_io", + CTLFLAG_RD, + &softc->unmappedio, + 0, + "Unmapped I/O leaf"); + + SYSCTL_ADD_INT(&softc->sysctl_ctx, + SYSCTL_CHILDREN(softc->sysctl_tree), + OID_AUTO, + "rotating", + CTLFLAG_RD, + &softc->rotating, + 0, + "Rotating media"); /* * Add some addressing info. @@ -1846,6 +1875,44 @@ dasysctlinit(void *context, int pending) &softc->wwpn, "World Wide Port Name"); } } + +#ifdef CAM_IO_STATS + /* + * Now add some useful stats. + * XXX These should live in cam_periph and be common to all periphs + */ + softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx, + SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats", + CTLFLAG_RD, 0, "Statistics"); + SYSCTL_ADD_INT(&softc->sysctl_stats_ctx, + SYSCTL_CHILDREN(softc->sysctl_stats_tree), + OID_AUTO, + "errors", + CTLFLAG_RD, + &softc->errors, + 0, + "Transport errors reported by the SIM"); + SYSCTL_ADD_INT(&softc->sysctl_stats_ctx, + SYSCTL_CHILDREN(softc->sysctl_stats_tree), + OID_AUTO, + "timeouts", + CTLFLAG_RD, + &softc->timeouts, + 0, + "Device timeouts reported by the SIM"); + SYSCTL_ADD_INT(&softc->sysctl_stats_ctx, + SYSCTL_CHILDREN(softc->sysctl_stats_tree), + OID_AUTO, + "pack_invalidations", + CTLFLAG_RD, + &softc->invalidations, + 0, + "Device pack invalidations"); +#endif + + cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx, + softc->sysctl_tree); + cam_periph_release(periph); } @@ -1904,6 +1971,26 @@ dacmdsizesysctl(SYSCTL_HANDLER_ARGS) return (0); } +static int +dasysctlsofttimeout(SYSCTL_HANDLER_ARGS) +{ + sbintime_t value; + int error; + + value = da_default_softtimeout / SBT_1MS; + + error = sysctl_handle_int(oidp, (int *)&value, 0, req); + if ((error != 0) || (req->newptr == NULL)) + return (error); + + /* XXX Should clip this to a reasonable level */ + if (value > da_default_timeout * 1000) + return (EINVAL); + + da_default_softtimeout = value * SBT_1MS; + return (0); +} + static void dadeletemethodset(struct da_softc *softc, da_delete_methods delete_method) { @@ -2075,14 +2162,18 @@ daregister(struct cam_periph *periph, void *arg) if (softc == NULL) { printf("daregister: Unable to probe new device. " - "Unable to allocate softc\n"); + "Unable to allocate softc\n"); return(CAM_REQ_CMP_ERR); } + if (cam_iosched_init(&softc->cam_iosched, periph) != 0) { + printf("daregister: Unable to probe new device. " + "Unable to allocate iosched memory\n"); + return(CAM_REQ_CMP_ERR); + } + LIST_INIT(&softc->pending_ccbs); softc->state = DA_STATE_PROBE_RC; - bioq_init(&softc->bio_queue); - bioq_init(&softc->delete_queue); bioq_init(&softc->delete_run_queue); if (SID_IS_REMOVABLE(&cgd->inq_data)) softc->flags |= DA_FLAG_PACK_REMOVABLE; @@ -2090,7 +2181,7 @@ daregister(struct cam_periph *periph, void *arg) softc->unmap_max_lba = UNMAP_RANGE_MAX; softc->ws_max_blks = WS16_MAX_BLKS; softc->trim_max_ranges = ATA_TRIM_MAX_RANGES; - softc->sort_io_queue = -1; + softc->rotating = 1; periph->softc = softc; @@ -2199,8 +2290,11 @@ daregister(struct cam_periph *periph, void *arg) softc->disk->d_flags = DISKFLAG_DIRECT_COMPLETION; if ((softc->quirks & DA_Q_NO_SYNC_CACHE) == 0) softc->disk->d_flags |= DISKFLAG_CANFLUSHCACHE; - if ((cpi.hba_misc & PIM_UNMAPPED) != 0) + if ((cpi.hba_misc & PIM_UNMAPPED) != 0) { + softc->unmappedio = 1; softc->disk->d_flags |= DISKFLAG_UNMAPPED_BIO; + xpt_print(periph->path, "UNMAPPED\n"); + } cam_strvis(softc->disk->d_descr, cgd->inq_data.vendor, sizeof(cgd->inq_data.vendor), sizeof(softc->disk->d_descr)); strlcat(softc->disk->d_descr, " ", sizeof(softc->disk->d_descr)); @@ -2277,23 +2371,11 @@ dastart(struct cam_periph *periph, union ccb *start_ccb) struct bio *bp; uint8_t tag_code; - /* Run BIO_DELETE if not running yet. */ - if (!softc->delete_running && - (bp = bioq_first(&softc->delete_queue)) != NULL) { - if (softc->delete_func != NULL) { - softc->delete_func(periph, start_ccb, bp); - goto out; - } else { - bioq_flush(&softc->delete_queue, NULL, 0); - /* FALLTHROUGH */ - } - } - - /* Run regular command. */ - bp = bioq_takefirst(&softc->bio_queue); +more: + bp = cam_iosched_next_bio(softc->cam_iosched); if (bp == NULL) { - if (softc->tur) { - softc->tur = 0; + if (cam_iosched_has_work_flags(softc->cam_iosched, DA_WORK_TUR)) { + cam_iosched_clr_work_flags(softc->cam_iosched, DA_WORK_TUR); scsi_test_unit_ready(&start_ccb->csio, /*retries*/ da_retry_count, dadone, @@ -2307,9 +2389,21 @@ dastart(struct cam_periph *periph, union ccb *start_ccb) xpt_release_ccb(start_ccb); break; } - if (softc->tur) { - softc->tur = 0; - cam_periph_release_locked(periph); + + if (bp->bio_cmd == BIO_DELETE) { + if (softc->delete_func != NULL) { + softc->delete_func(periph, start_ccb, bp); + goto out; + } else { + /* Not sure this is possible, but failsafe by lying and saying "sure, done." */ + biofinish(bp, NULL, 0); + goto more; + } + } + + if (cam_iosched_has_work_flags(softc->cam_iosched, DA_WORK_TUR)) { + cam_iosched_clr_work_flags(softc->cam_iosched, DA_WORK_TUR); + cam_periph_release_locked(periph); /* XXX is this still valid? I think so but unverified */ } if ((bp->bio_flags & BIO_ORDERED) != 0 || @@ -2377,6 +2471,7 @@ dastart(struct cam_periph *periph, union ccb *start_ccb) } start_ccb->ccb_h.ccb_state = DA_CCB_BUFFER_IO; start_ccb->ccb_h.flags |= CAM_UNLOCKED; + start_ccb->ccb_h.softtimeout = sbttotv(da_default_softtimeout); out: LIST_INSERT_HEAD(&softc->pending_ccbs, @@ -2625,11 +2720,19 @@ da_delete_unmap(struct cam_periph *periph, union ccb *ccb, struct bio *bp) * fewer LBA's than requested. */ - softc->delete_running = 1; bzero(softc->unmap_buf, sizeof(softc->unmap_buf)); bp1 = bp; do { - bioq_remove(&softc->delete_queue, bp1); + /* + * Note: ada and da are different in how they store the + * pending bp's in a trim. ada stores all of them in the + * trim_req.bps. da stores all but the first one in the + * delete_run_queue. ada then completes all the bps in + * its adadone() loop. da completes all the bps in the + * delete_run_queue in dadone, and relies on the biodone + * after to complete. This should be reconciled since there's + * no real reason to do it differently. XXX + */ if (bp1 != bp) bioq_insert_tail(&softc->delete_run_queue, bp1); lba = bp1->bio_pblkno; @@ -2669,11 +2772,15 @@ da_delete_unmap(struct cam_periph *periph, union ccb *ccb, struct bio *bp) lastcount = c; } lastlba = lba; - bp1 = bioq_first(&softc->delete_queue); - if (bp1 == NULL || ranges >= softc->unmap_max_ranges || - totalcount + bp1->bio_bcount / - softc->params.secsize > softc->unmap_max_lba) + bp1 = cam_iosched_next_trim(softc->cam_iosched); + if (bp1 == NULL) break; + if (ranges >= softc->unmap_max_ranges || + totalcount + bp1->bio_bcount / + softc->params.secsize > softc->unmap_max_lba) { + cam_iosched_put_back_trim(softc->cam_iosched, bp1); + break; + } } while (1); scsi_ulto2b(ranges * 16 + 6, &buf[0]); scsi_ulto2b(ranges * 16, &buf[2]); @@ -2689,6 +2796,7 @@ da_delete_unmap(struct cam_periph *periph, union ccb *ccb, struct bio *bp) da_default_timeout * 1000); ccb->ccb_h.ccb_state = DA_CCB_DELETE; ccb->ccb_h.flags |= CAM_UNLOCKED; + cam_iosched_submit_trim(softc->cam_iosched); } static void @@ -2703,12 +2811,10 @@ da_delete_trim(struct cam_periph *periph, union ccb *ccb, struct bio *bp) uint32_t lastcount = 0, c, requestcount; int ranges = 0, off, block_count; - softc->delete_running = 1; bzero(softc->unmap_buf, sizeof(softc->unmap_buf)); bp1 = bp; do { - bioq_remove(&softc->delete_queue, bp1); - if (bp1 != bp) + if (bp1 != bp)//XXX imp XXX bioq_insert_tail(&softc->delete_run_queue, bp1); lba = bp1->bio_pblkno; count = bp1->bio_bcount / softc->params.secsize; @@ -2752,10 +2858,14 @@ da_delete_trim(struct cam_periph *periph, union ccb *ccb, struct bio *bp) } } lastlba = lba; - bp1 = bioq_first(&softc->delete_queue); - if (bp1 == NULL || bp1->bio_bcount / softc->params.secsize > - (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) + bp1 = cam_iosched_next_trim(softc->cam_iosched); + if (bp1 == NULL) break; + if (bp1->bio_bcount / softc->params.secsize > + (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) { + cam_iosched_put_back_trim(softc->cam_iosched, bp1); + break; + } } while (1); block_count = (ranges + ATA_DSM_BLK_RANGES - 1) / ATA_DSM_BLK_RANGES; @@ -2770,6 +2880,7 @@ da_delete_trim(struct cam_periph *periph, union ccb *ccb, struct bio *bp) da_default_timeout * 1000); ccb->ccb_h.ccb_state = DA_CCB_DELETE; ccb->ccb_h.flags |= CAM_UNLOCKED; + cam_iosched_submit_trim(softc->cam_iosched); } /* @@ -2788,13 +2899,11 @@ da_delete_ws(struct cam_periph *periph, union ccb *ccb, struct bio *bp) softc = (struct da_softc *)periph->softc; ws_max_blks = softc->disk->d_delmaxsize / softc->params.secsize; - softc->delete_running = 1; lba = bp->bio_pblkno; count = 0; bp1 = bp; do { - bioq_remove(&softc->delete_queue, bp1); - if (bp1 != bp) + if (bp1 != bp)//XXX imp XXX bioq_insert_tail(&softc->delete_run_queue, bp1); count += bp1->bio_bcount / softc->params.secsize; if (count > ws_max_blks) { @@ -2805,11 +2914,15 @@ da_delete_ws(struct cam_periph *periph, union ccb *ccb, struct bio *bp) count = omin(count, ws_max_blks); break; } - bp1 = bioq_first(&softc->delete_queue); - if (bp1 == NULL || lba + count != bp1->bio_pblkno || - count + bp1->bio_bcount / - softc->params.secsize > ws_max_blks) + bp1 = cam_iosched_next_trim(softc->cam_iosched); + if (bp1 == NULL) break; + if (lba + count != bp1->bio_pblkno || + count + bp1->bio_bcount / + softc->params.secsize > ws_max_blks) { + cam_iosched_put_back_trim(softc->cam_iosched, bp1); + break; + } } while (1); scsi_write_same(&ccb->csio, @@ -2827,6 +2940,7 @@ da_delete_ws(struct cam_periph *periph, union ccb *ccb, struct bio *bp) da_default_timeout * 1000); ccb->ccb_h.ccb_state = DA_CCB_DELETE; ccb->ccb_h.flags |= CAM_UNLOCKED; + cam_iosched_submit_trim(softc->cam_iosched); } static int @@ -2870,8 +2984,8 @@ cmd6workaround(union ccb *ccb) da_delete_method_desc[softc->delete_method]); while ((bp = bioq_takefirst(&softc->delete_run_queue)) != NULL) - bioq_disksort(&softc->delete_queue, bp); - bioq_disksort(&softc->delete_queue, + cam_iosched_queue_work(softc->cam_iosched, bp); + cam_iosched_queue_work(softc->cam_iosched, (struct bio *)ccb->ccb_h.ccb_bp); ccb->ccb_h.ccb_bp = NULL; return (0); @@ -2998,9 +3112,12 @@ dadone(struct cam_periph *periph, union ccb *done_ccb) xpt_print(periph->path, "Invalidating pack\n"); softc->flags |= DA_FLAG_PACK_INVALID; +#ifdef CAM_IO_STATS + softc->invalidations++; +#endif queued_error = ENXIO; } - bioq_flush(&softc->bio_queue, NULL, + cam_iosched_flush(softc->cam_iosched, NULL, queued_error); if (bp != NULL) { bp->bio_error = error; @@ -3043,6 +3160,7 @@ dadone(struct cam_periph *periph, union ccb *done_ccb) if (LIST_EMPTY(&softc->pending_ccbs)) softc->flags |= DA_FLAG_WAS_OTAG; + cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb); xpt_release_ccb(done_ccb); if (state == DA_CCB_DELETE) { TAILQ_HEAD(, bio) queue; @@ -3060,7 +3178,7 @@ dadone(struct cam_periph *periph, union ccb *done_ccb) * and call daschedule again so that we don't stall if * there are no other I/Os pending apart from BIO_DELETEs. */ - softc->delete_running = 0; + cam_iosched_trim_done(softc->cam_iosched); daschedule(periph); cam_periph_unlock(periph); while ((bp1 = TAILQ_FIRST(&queue)) != NULL) { @@ -3073,8 +3191,10 @@ dadone(struct cam_periph *periph, union ccb *done_ccb) bp1->bio_resid = 0; biodone(bp1); } - } else + } else { + daschedule(periph); cam_periph_unlock(periph); + } if (bp != NULL) biodone(bp); return; @@ -3459,7 +3579,8 @@ dadone(struct cam_periph *periph, union ccb *done_ccb) scsi_2btoul(bdc->medium_rotation_rate); if (softc->disk->d_rotation_rate == SVPD_BDC_RATE_NON_ROTATING) { - softc->sort_io_queue = 0; + cam_iosched_set_sort_queue(softc->cam_iosched, 0); + softc->rotating = 0; } if (softc->disk->d_rotation_rate != old_rate) { disk_attr_changed(softc->disk, @@ -3521,9 +3642,9 @@ dadone(struct cam_periph *periph, union ccb *done_ccb) ata_params->media_rotation_rate; if (softc->disk->d_rotation_rate == ATA_RATE_NON_ROTATING) { - softc->sort_io_queue = 0; + cam_iosched_set_sort_queue(softc->cam_iosched, 0); + softc->rotating = 0; } - if (softc->disk->d_rotation_rate != old_rate) { disk_attr_changed(softc->disk, "GEOM::rotation_rate", M_NOWAIT); @@ -3652,6 +3773,25 @@ daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags) if (error == ERESTART) return (ERESTART); + switch (ccb->ccb_h.status & CAM_STATUS_MASK) { + case CAM_CMD_TIMEOUT: +#ifdef CAM_IO_STATS + softc->timeouts++; +#endif + break; + case CAM_REQ_ABORTED: + case CAM_REQ_CMP_ERR: + case CAM_REQ_TERMIO: + case CAM_UNREC_HBA_ERROR: + case CAM_DATA_RUN_ERR: +#ifdef CAM_IO_STATS + softc->errors++; +#endif + break; + default: + break; + } + /* * XXX * Until we have a better way of doing pack validation, @@ -3671,9 +3811,10 @@ damediapoll(void *arg) struct cam_periph *periph = arg; struct da_softc *softc = periph->softc; - if (!softc->tur && LIST_EMPTY(&softc->pending_ccbs)) { + if (!cam_iosched_has_work_flags(softc->cam_iosched, DA_WORK_TUR) && + LIST_EMPTY(&softc->pending_ccbs)) { if (cam_periph_acquire(periph) == CAM_REQ_CMP) { - softc->tur = 1; + cam_iosched_set_work_flags(softc->cam_iosched, DA_WORK_TUR); daschedule(periph); } } diff --git a/sys/conf/files b/sys/conf/files index 46e9768ee4b9..8831f5c2eb6c 100644 --- a/sys/conf/files +++ b/sys/conf/files @@ -68,6 +68,7 @@ usbdevs_data.h optional usb \ clean "usbdevs_data.h" cam/cam.c optional scbus cam/cam_compat.c optional scbus +cam/cam_iosched.c optional scbus cam/cam_periph.c optional scbus cam/cam_queue.c optional scbus cam/cam_sim.c optional scbus diff --git a/sys/conf/options b/sys/conf/options index 2283705d2860..11e778fc25da 100644 --- a/sys/conf/options +++ b/sys/conf/options @@ -329,6 +329,7 @@ CAM_DEBUG_TARGET opt_cam.h CAM_DEBUG_LUN opt_cam.h CAM_DEBUG_FLAGS opt_cam.h CAM_BOOT_DELAY opt_cam.h +CAM_NETFLIX_IOSCHED opt_cam.h SCSI_DELAY opt_scsi.h SCSI_NO_SENSE_STRINGS opt_scsi.h SCSI_NO_OP_STRINGS opt_scsi.h diff --git a/sys/dev/ahci/ahci.c b/sys/dev/ahci/ahci.c index 8341f662dd50..b27e30df5252 100644 --- a/sys/dev/ahci/ahci.c +++ b/sys/dev/ahci/ahci.c @@ -2417,6 +2417,9 @@ ahci_setup_fis(struct ahci_channel *ch, struct ahci_cmd_tab *ctp, union ccb *ccb fis[13] = ccb->ataio.cmd.sector_count_exp; } fis[15] = ATA_A_4BIT; + /* Gross and vile hack -- makes ncq trim work w/o changing ataio size */ + if (ccb->ataio.cmd.flags & CAM_ATAIO_AUX_HACK) + fis[16] = 1; } else { fis[15] = ccb->ataio.cmd.control; } @@ -2674,7 +2677,7 @@ ahciaction(struct cam_sim *sim, union ccb *ccb) if (ch->caps & AHCI_CAP_SPM) cpi->hba_inquiry |= PI_SATAPM; cpi->target_sprt = 0; - cpi->hba_misc = PIM_SEQSCAN | PIM_UNMAPPED; + cpi->hba_misc = PIM_SEQSCAN | PIM_UNMAPPED | PIM_NCQ_KLUDGE; cpi->hba_eng_cnt = 0; if (ch->caps & AHCI_CAP_SPM) cpi->max_target = 15; From 4bd916567e12ac84ae977d57f1153687d5a25c8a Mon Sep 17 00:00:00 2001 From: "Andrey V. Elsukov" Date: Thu, 14 Apr 2016 21:52:31 +0000 Subject: [PATCH 063/143] Change the type of 'etlv' field in struct named_object to uint16_t. It should match with the type field in struct ipfw_obj_tlv. Obtained from: Yandex LLC Sponsored by: Yandex LLC --- sys/netpfil/ipfw/ip_fw_private.h | 6 +++--- sys/netpfil/ipfw/ip_fw_sockopt.c | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/sys/netpfil/ipfw/ip_fw_private.h b/sys/netpfil/ipfw/ip_fw_private.h index 659af35fdd2c..97c1a78eddf8 100644 --- a/sys/netpfil/ipfw/ip_fw_private.h +++ b/sys/netpfil/ipfw/ip_fw_private.h @@ -313,9 +313,9 @@ struct named_object { TAILQ_ENTRY(named_object) nn_next; /* namehash */ TAILQ_ENTRY(named_object) nv_next; /* valuehash */ char *name; /* object name */ - uint8_t subtype; /* object subtype within class */ - uint8_t etlv; /* Export TLV id */ - uint16_t spare[2]; + uint16_t etlv; /* Export TLV id */ + uint8_t subtype;/* object subtype within class */ + uint8_t spare[3]; uint16_t kidx; /* object kernel index */ uint32_t set; /* set object belongs to */ uint32_t refcnt; /* number of references */ diff --git a/sys/netpfil/ipfw/ip_fw_sockopt.c b/sys/netpfil/ipfw/ip_fw_sockopt.c index 126466155c56..814445162939 100644 --- a/sys/netpfil/ipfw/ip_fw_sockopt.c +++ b/sys/netpfil/ipfw/ip_fw_sockopt.c @@ -4063,7 +4063,8 @@ ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set, hash = ni->hash_f(ni, name, set) % ni->nn_size; TAILQ_FOREACH(no, &ni->names[hash], nn_next) { - if (ni->cmp_f(no, name, set) == 0 && no->etlv == type) + if (ni->cmp_f(no, name, set) == 0 && + no->etlv == (uint16_t)type) return (no); } From a30ecd42b8e092742eb46cbfe4dd3cc9421a4d9e Mon Sep 17 00:00:00 2001 From: Scott Long Date: Thu, 14 Apr 2016 21:55:42 +0000 Subject: [PATCH 064/143] Add a devctl/devd notification conduit for CAM errors that happen at the periph level. When a relevant error is reported to the periph, some amplifying information is gathered, and the error and information are fed to devctl with the attributes / keys system=CAM, subsystem=periph. The 'type' key will be either 'error' or 'timeout', and based on this, various other keys are also populated. The purpose of this is to provide a concise mechanism for error reporting that is less noisy than the system console but higher in resolution and fidelity than simple sysctl counters. We will be using it at Netflix to populate a structured log and database to track errors and error trends across our world-wide population of drives. Submitted by: imp, scottl Approved by: kenm MFC after: 3 days Sponsored by: Netflix Differential Revision: D5943 --- sys/cam/cam_periph.c | 102 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 100 insertions(+), 2 deletions(-) diff --git a/sys/cam/cam_periph.c b/sys/cam/cam_periph.c index 91cb45d371d7..299b4ec41aa5 100644 --- a/sys/cam/cam_periph.c +++ b/sys/cam/cam_periph.c @@ -86,6 +86,7 @@ static int camperiphscsisenseerror(union ccb *ccb, u_int32_t *timeout, u_int32_t *action, const char **action_string); +static void cam_periph_devctl_notify(union ccb *ccb); static int nperiph_drivers; static int initialized = 0; @@ -1615,7 +1616,7 @@ cam_periph_error(union ccb *ccb, cam_flags camflags, struct cam_periph *periph; const char *action_string; cam_status status; - int frozen, error, openings; + int frozen, error, openings, devctl_err; u_int32_t action, relsim_flags, timeout; action = SSQ_PRINT_SENSE; @@ -1624,9 +1625,26 @@ cam_periph_error(union ccb *ccb, cam_flags camflags, status = ccb->ccb_h.status; frozen = (status & CAM_DEV_QFRZN) != 0; status &= CAM_STATUS_MASK; - openings = relsim_flags = timeout = 0; + devctl_err = openings = relsim_flags = timeout = 0; orig_ccb = ccb; + /* Filter the errors that should be reported via devctl */ + switch (ccb->ccb_h.status & CAM_STATUS_MASK) { + case CAM_CMD_TIMEOUT: + case CAM_REQ_ABORTED: + case CAM_REQ_CMP_ERR: + case CAM_REQ_TERMIO: + case CAM_UNREC_HBA_ERROR: + case CAM_DATA_RUN_ERR: + case CAM_SCSI_STATUS_ERROR: + case CAM_ATA_STATUS_ERROR: + case CAM_SMP_STATUS_ERROR: + devctl_err++; + break; + default: + break; + } + switch (status) { case CAM_REQ_CMP: error = 0; @@ -1754,6 +1772,9 @@ cam_periph_error(union ccb *ccb, cam_flags camflags, xpt_print(ccb->ccb_h.path, "Retrying command\n"); } + if (devctl_err) + cam_periph_devctl_notify(orig_ccb); + if ((action & SSQ_LOST) != 0) { lun_id_t lun_id; @@ -1824,3 +1845,80 @@ cam_periph_error(union ccb *ccb, cam_flags camflags, return (error); } + +#define CAM_PERIPH_DEVD_MSG_SIZE 256 + +static void +cam_periph_devctl_notify(union ccb *ccb) +{ + struct cam_periph *periph; + struct ccb_getdev *cgd; + struct sbuf sb; + int serr, sk, asc, ascq; + char *sbmsg, *type; + + sbmsg = malloc(CAM_PERIPH_DEVD_MSG_SIZE, M_CAMPERIPH, M_NOWAIT); + if (sbmsg == NULL) + return; + + sbuf_new(&sb, sbmsg, CAM_PERIPH_DEVD_MSG_SIZE, SBUF_FIXEDLEN); + + periph = xpt_path_periph(ccb->ccb_h.path); + sbuf_printf(&sb, "device=%s%d ", periph->periph_name, + periph->unit_number); + + sbuf_printf(&sb, "serial=\""); + if ((cgd = (struct ccb_getdev *)xpt_alloc_ccb_nowait()) != NULL) { + xpt_setup_ccb(&cgd->ccb_h, ccb->ccb_h.path, + CAM_PRIORITY_NORMAL); + cgd->ccb_h.func_code = XPT_GDEV_TYPE; + xpt_action((union ccb *)cgd); + + if (cgd->ccb_h.status == CAM_REQ_CMP) + sbuf_bcat(&sb, cgd->serial_num, cgd->serial_num_len); + } + sbuf_printf(&sb, "\" "); + sbuf_printf(&sb, "cam_status=\"0x%x\" ", ccb->ccb_h.status); + + switch (ccb->ccb_h.status & CAM_STATUS_MASK) { + case CAM_CMD_TIMEOUT: + sbuf_printf(&sb, "timeout=%d ", ccb->ccb_h.timeout); + type = "timeout"; + break; + case CAM_SCSI_STATUS_ERROR: + sbuf_printf(&sb, "scsi_status=%d ", ccb->csio.scsi_status); + if (scsi_extract_sense_ccb(ccb, &serr, &sk, &asc, &ascq)) + sbuf_printf(&sb, "scsi_sense=\"%02x %02x %02x %02x\" ", + serr, sk, asc, ascq); + type = "error"; + break; + case CAM_ATA_STATUS_ERROR: + sbuf_printf(&sb, "RES=\""); + ata_res_sbuf(&ccb->ataio.res, &sb); + sbuf_printf(&sb, "\" "); + type = "error"; + break; + default: + type = "error"; + break; + } + + if (ccb->ccb_h.func_code == XPT_SCSI_IO) { + sbuf_printf(&sb, "CDB=\""); + if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) + scsi_cdb_sbuf(ccb->csio.cdb_io.cdb_ptr, &sb); + else + scsi_cdb_sbuf(ccb->csio.cdb_io.cdb_bytes, &sb); + sbuf_printf(&sb, "\" "); + } else if (ccb->ccb_h.func_code == XPT_ATA_IO) { + sbuf_printf(&sb, "ACB=\""); + ata_cmd_sbuf(&ccb->ataio.cmd, &sb); + sbuf_printf(&sb, "\" "); + } + + if (sbuf_finish(&sb) == 0) + devctl_notify("CAM", "periph", type, sbuf_data(&sb)); + sbuf_delete(&sb); + free(sbmsg, M_CAMPERIPH); +} + From 4a2e0710e175d9207e816d1f0df85a4356cafb2a Mon Sep 17 00:00:00 2001 From: Warren Block Date: Thu, 14 Apr 2016 21:56:36 +0000 Subject: [PATCH 065/143] Remove a link to the CTM section of the Handbook, which no longer exists. MFC after: 1 week --- usr.sbin/ctm/ctm/ctm.1 | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/usr.sbin/ctm/ctm/ctm.1 b/usr.sbin/ctm/ctm/ctm.1 index 6ba35c9c51e1..819a14b7fadd 100644 --- a/usr.sbin/ctm/ctm/ctm.1 +++ b/usr.sbin/ctm/ctm/ctm.1 @@ -12,7 +12,7 @@ .\" .\" $FreeBSD$ .\" -.Dd December 14, 2015 +.Dd April 14, 2016 .Dt CTM 1 .Os .Sh NAME @@ -308,11 +308,6 @@ options. .Xr ctm_smail 1 , .Xr ctm 5 .Rs -.%B "The FreeBSD Handbook" -.%T "Using CTM" -.%U http://www.FreeBSD.org/doc/en_US.ISO8859-1/books/handbook/ctm.html -.Re -.Rs .%T "Miscellaneous CTM on FreeBSD Resources" .%U http://ctm.berklix.org .Re From 473fda75dd6cfc7a637a1e63c0295bd09a44fe23 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 22:00:33 +0000 Subject: [PATCH 066/143] META_MODE+filemon: Default -DNO_CLEAN enabled. When using meta mode with filemon, the build is reliably incremental safe. Bmake will use the meta files, along with filemon information, to rebuild targets when their dependencies change, commands change, or files they generate are missing. Sponsored by: EMC / Isilon Storage Division --- Makefile.inc1 | 9 +++++++++ share/man/man7/build.7 | 10 +++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Makefile.inc1 b/Makefile.inc1 index 28dc8fbfc4e5..65b0ebc0ab92 100644 --- a/Makefile.inc1 +++ b/Makefile.inc1 @@ -144,6 +144,15 @@ CLEANDIR= clean cleandepend CLEANDIR= cleandir .endif +.if ${MK_META_MODE} == "yes" +# If filemon is used then we can rely on the build being incremental-safe. +# The .meta files will also track the build command and rebuild should +# it change. +.if empty(.MAKE.MODE:Mnofilemon) +NO_CLEAN= t +.endif +.endif + LOCAL_TOOL_DIRS?= PACKAGEDIR?= ${DESTDIR}/${DISTDIR} diff --git a/share/man/man7/build.7 b/share/man/man7/build.7 index 36603dac5ac3..a605c2846bd2 100644 --- a/share/man/man7/build.7 +++ b/share/man/man7/build.7 @@ -24,7 +24,7 @@ .\" .\" $FreeBSD$ .\" -.Dd March 29, 2016 +.Dd April 14, 2016 .Dt BUILD 7 .Os .Sh NAME @@ -539,6 +539,14 @@ instead of .Dq make cleandir . .It Va NO_CLEAN If set, no object tree files are cleaned at all. +This is the default when +.Va WITH_META_MODE +is used with +.Xr filemon 4 +loaded. +See +.Xr src.conf 5 +for more details. Setting .Va NO_CLEAN implies From f43bc6d18d4e5d5c88302614caacfb085c62ae91 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 22:00:49 +0000 Subject: [PATCH 067/143] Add more content for WITH_META_MODE/WITH_DIRDEPS_BUILD. Sponsored by: EMC / Isilon Storage Division --- tools/build/options/WITH_DIRDEPS_BUILD | 20 ++++++-------- tools/build/options/WITH_META_MODE | 37 +++++++++++++++++++++++--- 2 files changed, 41 insertions(+), 16 deletions(-) diff --git a/tools/build/options/WITH_DIRDEPS_BUILD b/tools/build/options/WITH_DIRDEPS_BUILD index 981c1a93db11..334c483c9ca5 100644 --- a/tools/build/options/WITH_DIRDEPS_BUILD +++ b/tools/build/options/WITH_DIRDEPS_BUILD @@ -1,9 +1,9 @@ .\" $FreeBSD$ -Enable building in meta mode. -This is an experimental build feature. +This is an experimental build system. For details see http://www.crufty.net/sjg/docs/freebsd-meta-mode.htm. -.Pp +Build commands can be seen from the top-level with: +.Dl make show-valid-targets The build is driven by dirdeps.mk using .Va DIRDEPS stored in @@ -23,17 +23,13 @@ and child directories. .Va NO_DIRDEPS_BELOW will skip building any dirdeps and only build the current directory. .Pp -As each target is made -.Xr make 1 -produces a meta file which is used to capture (and compare) -the command line, -as well as any command output. -If -.Xr filemon 4 -is available the meta file will also capture a record of files -used to produce the target by tracking syscalls. +This also utilizes the +.Va WITH_META_MODE +logic for incremental builds. .Pp The build will hide commands ran unless .Va NO_SILENT is defined. .Pp +Note that there is currently no mass install feature for this. +.Pp diff --git a/tools/build/options/WITH_META_MODE b/tools/build/options/WITH_META_MODE index 906b557769c9..1d19be1ea4ca 100644 --- a/tools/build/options/WITH_META_MODE +++ b/tools/build/options/WITH_META_MODE @@ -1,12 +1,41 @@ .\" $FreeBSD$ -Create meta files when not doing DIRDEPS_BUILD. +Creates +.Xr make 1 +meta files when building, which can provide a reliable incremental build when +using +.Xr filemon 4 . +The meta file is created in the OBJDIR as +.Pa target.meta . +These meta files track the command ran, its output, and the current directory. When the .Xr filemon 4 -module is loaded, dependencies will be tracked for all commands. -If any command, its dependencies, or files it generates are missing then -the target will be considered out-of-date and rebuilt. +module is loaded, any files used by the commands executed will be tracked as +dependencies for the target in its meta file. +The target will be considered out-of-date and rebuilt if any of the following +are true compared to the last build: +.Bl -bullet -compact +.It +The command to execute changes. +.It +The current working directory changes. +.It +The target's meta file is missing. +.It +[requires +.Xr filemon 4 ] +Files read, executed or linked to are newer than the target. +.It +[requires +.Xr filemon 4 ] +Files read, written, executed or linked are missing. +.El The meta files can also be useful for debugging. .Pp The build will hide commands ran unless .Va NO_SILENT is defined. +.Pp +The build operates as it normally would otherwise. +This option originally invoked a different build system but that was renamed +to +.Va WITH_DIRDEPS_BUILD . From 846c7c0841dbef1e291b9a3d5e4b5c900c730be2 Mon Sep 17 00:00:00 2001 From: Scott Long Date: Thu, 14 Apr 2016 22:03:23 +0000 Subject: [PATCH 068/143] Update the devd.conf man page to describe the new CAM/periph system/subsystem. MFC after: 3 days Sponsored by: Netflix --- sbin/devd/devd.conf.5 | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/sbin/devd/devd.conf.5 b/sbin/devd/devd.conf.5 index 83c4c767400a..b358dcb325b1 100644 --- a/sbin/devd/devd.conf.5 +++ b/sbin/devd/devd.conf.5 @@ -41,7 +41,7 @@ .\" ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS .\" SOFTWARE. .\" -.Dd March 28, 2016 +.Dd April 14, 2016 .Dt DEVD.CONF 5 .Os .Sh NAME @@ -501,6 +501,23 @@ Information about the state of the system. Notification that the system has woken from the suspended state. .El .El +.Pp +.It Li CAM +Events related to the +.Xr cam 4 +system. +.Bl -tag -width ".Sy Subsystem" -compact +.It Sy Subsystem +.It Li periph +Events related to peripheral devices. +.Bl -tag -width ".li timeout" -compact +.It Sy Type +.It Li error +Generic errors. +.It Li timeout +Command timeouts. +.El +.El .El .Pp A link state change to UP on the interface @@ -630,4 +647,5 @@ has many additional examples. .Xr coretemp 4 , .Xr devfs 5 , .Xr re_format 7 , -.Xr devd 8 +.Xr devd 8 , +.Xr cam 4 From be894451fa0bc4e667ccd15f94d331227ac02b1d Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Thu, 14 Apr 2016 22:10:37 +0000 Subject: [PATCH 069/143] Regenerate --- share/man/man5/src.conf.5 | 63 +++++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 19 deletions(-) diff --git a/share/man/man5/src.conf.5 b/share/man/man5/src.conf.5 index 0d30a168688d..e9326f24e554 100644 --- a/share/man/man5/src.conf.5 +++ b/share/man/man5/src.conf.5 @@ -1,7 +1,7 @@ .\" DO NOT EDIT-- this file is automatically generated. .\" from FreeBSD: head/tools/build/options/makeman 292283 2015-12-15 18:42:30Z bdrewery .\" $FreeBSD$ -.Dd April 13, 2016 +.Dd April 14, 2016 .Dt SRC.CONF 5 .Os .Sh NAME @@ -473,12 +473,12 @@ executable binary and shared library. .\" from FreeBSD: head/tools/build/options/WITHOUT_DICT 156932 2006-03-21 07:50:50Z ru Set to not build the Webster dictionary files. .It Va WITH_DIRDEPS_BUILD -.\" from FreeBSD: head/tools/build/options/WITH_DIRDEPS_BUILD 297843 2016-04-12 03:37:42Z bdrewery -Enable building in meta mode. -This is an experimental build feature. +.\" from FreeBSD: head/tools/build/options/WITH_DIRDEPS_BUILD 298007 2016-04-14 22:00:49Z bdrewery +This is an experimental build system. For details see http://www.crufty.net/sjg/docs/freebsd-meta-mode.htm. -.Pp +Build commands can be seen from the top-level with: +.Dl make show-valid-targets The build is driven by dirdeps.mk using .Va DIRDEPS stored in @@ -498,20 +498,16 @@ and child directories. .Va NO_DIRDEPS_BELOW will skip building any dirdeps and only build the current directory. .Pp -As each target is made -.Xr make 1 -produces a meta file which is used to capture (and compare) -the command line, -as well as any command output. -If -.Xr filemon 4 -is available the meta file will also capture a record of files -used to produce the target by tracking syscalls. +This also utilizes the +.Va WITH_META_MODE +logic for incremental builds. .Pp The build will hide commands ran unless .Va NO_SILENT is defined. .Pp +Note that there is currently no mass install feature for this. +.Pp When set, it also enforces the following options: .Pp .Bl -item -compact @@ -1062,19 +1058,48 @@ Set to not build utilities for manual pages, .Xr manctl 8 , and related support files. .It Va WITH_META_MODE -.\" from FreeBSD: head/tools/build/options/WITH_META_MODE 297844 2016-04-12 03:40:13Z bdrewery -Create meta files when not doing DIRDEPS_BUILD. +.\" from FreeBSD: head/tools/build/options/WITH_META_MODE 298007 2016-04-14 22:00:49Z bdrewery +Creates +.Xr make 1 +meta files when building, which can provide a reliable incremental build when +using +.Xr filemon 4 . +The meta file is created in the OBJDIR as +.Pa target.meta . +These meta files track the command ran, its output, and the current directory. When the .Xr filemon 4 -module is loaded, dependencies will be tracked for all commands. -If any command, its dependencies, or files it generates are missing then -the target will be considered out-of-date and rebuilt. +module is loaded, any files used by the commands executed will be tracked as +dependencies for the target in its meta file. +The target will be considered out-of-date and rebuilt if any of the following +are true compared to the last build: +.Bl -bullet -compact +.It +The command to execute changes. +.It +The current working directory changes. +.It +The target's meta file is missing. +.It +[requires +.Xr filemon 4 ] +Files read, executed or linked to are newer than the target. +.It +[requires +.Xr filemon 4 ] +Files read, written, executed or linked are missing. +.El The meta files can also be useful for debugging. .Pp The build will hide commands ran unless .Va NO_SILENT is defined. .Pp +The build operates as it normally would otherwise. +This option originally invoked a different build system but that was renamed +to +.Va WITH_DIRDEPS_BUILD . +.Pp This must be set in the environment, make command line, or .Pa /etc/src-env.conf , not From ba6c22ce938ed5ba3f6e93549b8aae635f6ec272 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Thu, 14 Apr 2016 22:13:44 +0000 Subject: [PATCH 070/143] Add in missing files from r298002. --- sys/cam/cam_iosched.c | 1599 +++++++++++++++++++++++++++++++++++++++++ sys/cam/cam_iosched.h | 64 ++ 2 files changed, 1663 insertions(+) create mode 100644 sys/cam/cam_iosched.c create mode 100644 sys/cam/cam_iosched.h diff --git a/sys/cam/cam_iosched.c b/sys/cam/cam_iosched.c new file mode 100644 index 000000000000..b26eeac00ac8 --- /dev/null +++ b/sys/cam/cam_iosched.c @@ -0,0 +1,1599 @@ +/*- + * CAM IO Scheduler Interface + * + * Copyright (c) 2015 Netflix, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer, + * without modification, immediately at the beginning of the file. + * 2. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * $FreeBSD$ + */ + +#include "opt_cam.h" +#include "opt_ddb.h" + +#include +__FBSDID("$FreeBSD$"); + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +static MALLOC_DEFINE(M_CAMSCHED, "CAM I/O Scheduler", + "CAM I/O Scheduler buffers"); + +/* + * Default I/O scheduler for FreeBSD. This implementation is just a thin-vineer + * over the bioq_* interface, with notions of separate calls for normal I/O and + * for trims. + */ + +#ifdef CAM_NETFLIX_IOSCHED + +SYSCTL_DECL(_kern_cam); +static int do_netflix_iosched = 1; +TUNABLE_INT("kern.cam.do_netflix_iosched", &do_netflix_iosched); +SYSCTL_INT(_kern_cam, OID_AUTO, do_netflix_iosched, CTLFLAG_RD, + &do_netflix_iosched, 1, + "Enable Netflix I/O scheduler optimizations."); + +static int alpha_bits = 9; +TUNABLE_INT("kern.cam.iosched_alpha_bits", &alpha_bits); +SYSCTL_INT(_kern_cam, OID_AUTO, iosched_alpha_bits, CTLFLAG_RW, + &alpha_bits, 1, + "Bits in EMA's alpha."); + + + +struct iop_stats; +struct cam_iosched_softc; + +int iosched_debug = 0; + +typedef enum { + none = 0, /* No limits */ + queue_depth, /* Limit how many ops we queue to SIM */ + iops, /* Limit # of IOPS to the drive */ + bandwidth, /* Limit bandwidth to the drive */ + limiter_max +} io_limiter; + +static const char *cam_iosched_limiter_names[] = + { "none", "queue_depth", "iops", "bandwidth" }; + +/* + * Called to initialize the bits of the iop_stats structure relevant to the + * limiter. Called just after the limiter is set. + */ +typedef int l_init_t(struct iop_stats *); + +/* + * Called every tick. + */ +typedef int l_tick_t(struct iop_stats *); + +/* + * Called to see if the limiter thinks this IOP can be allowed to + * proceed. If so, the limiter assumes that the while IOP proceeded + * and makes any accounting of it that's needed. + */ +typedef int l_iop_t(struct iop_stats *, struct bio *); + +/* + * Called when an I/O completes so the limiter can updates its + * accounting. Pending I/Os may complete in any order (even when + * sent to the hardware at the same time), so the limiter may not + * make any assumptions other than this I/O has completed. If it + * returns 1, then xpt_schedule() needs to be called again. + */ +typedef int l_iodone_t(struct iop_stats *, struct bio *); + +static l_iop_t cam_iosched_qd_iop; +static l_iop_t cam_iosched_qd_caniop; +static l_iodone_t cam_iosched_qd_iodone; + +static l_init_t cam_iosched_iops_init; +static l_tick_t cam_iosched_iops_tick; +static l_iop_t cam_iosched_iops_caniop; +static l_iop_t cam_iosched_iops_iop; + +static l_init_t cam_iosched_bw_init; +static l_tick_t cam_iosched_bw_tick; +static l_iop_t cam_iosched_bw_caniop; +static l_iop_t cam_iosched_bw_iop; + +struct limswitch +{ + l_init_t *l_init; + l_tick_t *l_tick; + l_iop_t *l_iop; + l_iop_t *l_caniop; + l_iodone_t *l_iodone; +} limsw[] = +{ + { /* none */ + .l_init = NULL, + .l_tick = NULL, + .l_iop = NULL, + .l_iodone= NULL, + }, + { /* queue_depth */ + .l_init = NULL, + .l_tick = NULL, + .l_caniop = cam_iosched_qd_caniop, + .l_iop = cam_iosched_qd_iop, + .l_iodone= cam_iosched_qd_iodone, + }, + { /* iops */ + .l_init = cam_iosched_iops_init, + .l_tick = cam_iosched_iops_tick, + .l_caniop = cam_iosched_iops_caniop, + .l_iop = cam_iosched_iops_iop, + .l_iodone= NULL, + }, + { /* bandwidth */ + .l_init = cam_iosched_bw_init, + .l_tick = cam_iosched_bw_tick, + .l_caniop = cam_iosched_bw_caniop, + .l_iop = cam_iosched_bw_iop, + .l_iodone= NULL, + }, +}; + +struct iop_stats +{ + /* + * sysctl state for this subnode. + */ + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; + + /* + * Information about the current rate limiters, if any + */ + io_limiter limiter; /* How are I/Os being limited */ + int min; /* Low range of limit */ + int max; /* High range of limit */ + int current; /* Current rate limiter */ + int l_value1; /* per-limiter scratch value 1. */ + int l_value2; /* per-limiter scratch value 2. */ + + + /* + * Debug information about counts of I/Os that have gone through the + * scheduler. + */ + int pending; /* I/Os pending in the hardware */ + int queued; /* number currently in the queue */ + int total; /* Total for all time -- wraps */ + int in; /* number queued all time -- wraps */ + int out; /* number completed all time -- wraps */ + + /* + * Statistics on different bits of the process. + */ + /* Exp Moving Average, alpha = 1 / (1 << alpha_bits) */ + sbintime_t ema; + sbintime_t emss; /* Exp Moving sum of the squares */ + sbintime_t sd; /* Last computed sd */ + + struct cam_iosched_softc *softc; +}; + + +typedef enum { + set_max = 0, /* current = max */ + read_latency, /* Steer read latency by throttling writes */ + cl_max /* Keep last */ +} control_type; + +static const char *cam_iosched_control_type_names[] = + { "set_max", "read_latency" }; + +struct control_loop +{ + /* + * sysctl state for this subnode. + */ + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; + + sbintime_t next_steer; /* Time of next steer */ + sbintime_t steer_interval; /* How often do we steer? */ + sbintime_t lolat; + sbintime_t hilat; + int alpha; + control_type type; /* What type of control? */ + int last_count; /* Last I/O count */ + + struct cam_iosched_softc *softc; +}; + +#endif + +struct cam_iosched_softc +{ + struct bio_queue_head bio_queue; + struct bio_queue_head trim_queue; + /* scheduler flags < 16, user flags >= 16 */ + uint32_t flags; + int sort_io_queue; +#ifdef CAM_NETFLIX_IOSCHED + int read_bias; /* Read bias setting */ + int current_read_bias; /* Current read bias state */ + int total_ticks; + + struct bio_queue_head write_queue; + struct iop_stats read_stats, write_stats, trim_stats; + struct sysctl_ctx_list sysctl_ctx; + struct sysctl_oid *sysctl_tree; + + int quanta; /* Number of quanta per second */ + struct callout ticker; /* Callout for our quota system */ + struct cam_periph *periph; /* cam periph associated with this device */ + uint32_t this_frac; /* Fraction of a second (1024ths) for this tick */ + sbintime_t last_time; /* Last time we ticked */ + struct control_loop cl; +#endif +}; + +#ifdef CAM_NETFLIX_IOSCHED +/* + * helper functions to call the limsw functions. + */ +static int +cam_iosched_limiter_init(struct iop_stats *ios) +{ + int lim = ios->limiter; + + /* maybe this should be a kassert */ + if (lim < none || lim >= limiter_max) + return EINVAL; + + if (limsw[lim].l_init) + return limsw[lim].l_init(ios); + + return 0; +} + +static int +cam_iosched_limiter_tick(struct iop_stats *ios) +{ + int lim = ios->limiter; + + /* maybe this should be a kassert */ + if (lim < none || lim >= limiter_max) + return EINVAL; + + if (limsw[lim].l_tick) + return limsw[lim].l_tick(ios); + + return 0; +} + +static int +cam_iosched_limiter_iop(struct iop_stats *ios, struct bio *bp) +{ + int lim = ios->limiter; + + /* maybe this should be a kassert */ + if (lim < none || lim >= limiter_max) + return EINVAL; + + if (limsw[lim].l_iop) + return limsw[lim].l_iop(ios, bp); + + return 0; +} + +static int +cam_iosched_limiter_caniop(struct iop_stats *ios, struct bio *bp) +{ + int lim = ios->limiter; + + /* maybe this should be a kassert */ + if (lim < none || lim >= limiter_max) + return EINVAL; + + if (limsw[lim].l_caniop) + return limsw[lim].l_caniop(ios, bp); + + return 0; +} + +static int +cam_iosched_limiter_iodone(struct iop_stats *ios, struct bio *bp) +{ + int lim = ios->limiter; + + /* maybe this should be a kassert */ + if (lim < none || lim >= limiter_max) + return 0; + + if (limsw[lim].l_iodone) + return limsw[lim].l_iodone(ios, bp); + + return 0; +} + +/* + * Functions to implement the different kinds of limiters + */ + +static int +cam_iosched_qd_iop(struct iop_stats *ios, struct bio *bp) +{ + + if (ios->current <= 0 || ios->pending < ios->current) + return 0; + + return EAGAIN; +} + +static int +cam_iosched_qd_caniop(struct iop_stats *ios, struct bio *bp) +{ + + if (ios->current <= 0 || ios->pending < ios->current) + return 0; + + return EAGAIN; +} + +static int +cam_iosched_qd_iodone(struct iop_stats *ios, struct bio *bp) +{ + + if (ios->current <= 0 || ios->pending != ios->current) + return 0; + + return 1; +} + +static int +cam_iosched_iops_init(struct iop_stats *ios) +{ + + ios->l_value1 = ios->current / ios->softc->quanta; + if (ios->l_value1 <= 0) + ios->l_value1 = 1; + + return 0; +} + +static int +cam_iosched_iops_tick(struct iop_stats *ios) +{ + + ios->l_value1 = (int)((ios->current * (uint64_t)ios->softc->this_frac) >> 16); + if (ios->l_value1 <= 0) + ios->l_value1 = 1; + + return 0; +} + +static int +cam_iosched_iops_caniop(struct iop_stats *ios, struct bio *bp) +{ + + /* + * So if we have any more IOPs left, allow it, + * otherwise wait. + */ + if (ios->l_value1 <= 0) + return EAGAIN; + return 0; +} + +static int +cam_iosched_iops_iop(struct iop_stats *ios, struct bio *bp) +{ + int rv; + + rv = cam_iosched_limiter_caniop(ios, bp); + if (rv == 0) + ios->l_value1--; + + return rv; +} + +static int +cam_iosched_bw_init(struct iop_stats *ios) +{ + + /* ios->current is in kB/s, so scale to bytes */ + ios->l_value1 = ios->current * 1000 / ios->softc->quanta; + + return 0; +} + +static int +cam_iosched_bw_tick(struct iop_stats *ios) +{ + int bw; + + /* + * If we're in the hole for available quota from + * the last time, then add the quantum for this. + * If we have any left over from last quantum, + * then too bad, that's lost. Also, ios->current + * is in kB/s, so scale. + * + * We also allow up to 4 quanta of credits to + * accumulate to deal with burstiness. 4 is extremely + * arbitrary. + */ + bw = (int)((ios->current * 1000ull * (uint64_t)ios->softc->this_frac) >> 16); + if (ios->l_value1 < bw * 4) + ios->l_value1 += bw; + + return 0; +} + +static int +cam_iosched_bw_caniop(struct iop_stats *ios, struct bio *bp) +{ + /* + * So if we have any more bw quota left, allow it, + * otherwise wait. Not, we'll go negative and that's + * OK. We'll just get a lettle less next quota. + * + * Note on going negative: that allows us to process + * requests in order better, since we won't allow + * shorter reads to get around the long one that we + * don't have the quota to do just yet. It also prevents + * starvation by being a little more permissive about + * what we let through this quantum (to prevent the + * starvation), at the cost of getting a little less + * next quantum. + */ + if (ios->l_value1 <= 0) + return EAGAIN; + + + return 0; +} + +static int +cam_iosched_bw_iop(struct iop_stats *ios, struct bio *bp) +{ + int rv; + + rv = cam_iosched_limiter_caniop(ios, bp); + if (rv == 0) + ios->l_value1 -= bp->bio_length; + + return rv; +} + +static void cam_iosched_cl_maybe_steer(struct control_loop *clp); + +static void +cam_iosched_ticker(void *arg) +{ + struct cam_iosched_softc *isc = arg; + sbintime_t now, delta; + + callout_reset(&isc->ticker, hz / isc->quanta - 1, cam_iosched_ticker, isc); + + now = sbinuptime(); + delta = now - isc->last_time; + isc->this_frac = (uint32_t)delta >> 16; /* Note: discards seconds -- should be 0 harmless if not */ + isc->last_time = now; + + cam_iosched_cl_maybe_steer(&isc->cl); + + cam_iosched_limiter_tick(&isc->read_stats); + cam_iosched_limiter_tick(&isc->write_stats); + cam_iosched_limiter_tick(&isc->trim_stats); + + cam_iosched_schedule(isc, isc->periph); + + isc->total_ticks++; +} + + +static void +cam_iosched_cl_init(struct control_loop *clp, struct cam_iosched_softc *isc) +{ + + clp->next_steer = sbinuptime(); + clp->softc = isc; + clp->steer_interval = SBT_1S * 5; /* Let's start out steering every 5s */ + clp->lolat = 5 * SBT_1MS; + clp->hilat = 15 * SBT_1MS; + clp->alpha = 20; /* Alpha == gain. 20 = .2 */ + clp->type = set_max; +} + +static void +cam_iosched_cl_maybe_steer(struct control_loop *clp) +{ + struct cam_iosched_softc *isc; + sbintime_t now, lat; + int old; + + isc = clp->softc; + now = isc->last_time; + if (now < clp->next_steer) + return; + + clp->next_steer = now + clp->steer_interval; + switch (clp->type) { + case set_max: + if (isc->write_stats.current != isc->write_stats.max) + printf("Steering write from %d kBps to %d kBps\n", + isc->write_stats.current, isc->write_stats.max); + isc->read_stats.current = isc->read_stats.max; + isc->write_stats.current = isc->write_stats.max; + isc->trim_stats.current = isc->trim_stats.max; + break; + case read_latency: + old = isc->write_stats.current; + lat = isc->read_stats.ema; + /* + * Simple PLL-like engine. Since we're steering to a range for + * the SP (set point) that makes things a little more + * complicated. In addition, we're not directly controlling our + * PV (process variable), the read latency, but instead are + * manipulating the write bandwidth limit for our MV + * (manipulation variable), analysis of this code gets a bit + * messy. Also, the MV is a very noisy control surface for read + * latency since it is affected by many hidden processes inside + * the device which change how responsive read latency will be + * in reaction to changes in write bandwidth. Unlike the classic + * boiler control PLL. this may result in over-steering while + * the SSD takes its time to react to the new, lower load. This + * is why we use a relatively low alpha of between .1 and .25 to + * compensate for this effect. At .1, it takes ~22 steering + * intervals to back off by a factor of 10. At .2 it only takes + * ~10. At .25 it only takes ~8. However some preliminary data + * from the SSD drives suggests a reasponse time in 10's of + * seconds before latency drops regardless of the new write + * rate. Careful observation will be reqiured to tune this + * effectively. + * + * Also, when there's no read traffic, we jack up the write + * limit too regardless of the last read latency. 10 is + * somewhat arbitrary. + */ + if (lat < clp->lolat || isc->read_stats.total - clp->last_count < 10) + isc->write_stats.current = isc->write_stats.current * + (100 + clp->alpha) / 100; /* Scale up */ + else if (lat > clp->hilat) + isc->write_stats.current = isc->write_stats.current * + (100 - clp->alpha) / 100; /* Scale down */ + clp->last_count = isc->read_stats.total; + + /* + * Even if we don't steer, per se, enforce the min/max limits as + * those may have changed. + */ + if (isc->write_stats.current < isc->write_stats.min) + isc->write_stats.current = isc->write_stats.min; + if (isc->write_stats.current > isc->write_stats.max) + isc->write_stats.current = isc->write_stats.max; + if (old != isc->write_stats.current) + printf("Steering write from %d kBps to %d kBps due to latency of %ldus\n", + old, isc->write_stats.current, + ((uint64_t)1000000 * (uint32_t)lat) >> 32); + break; + case cl_max: + break; + } +} +#endif + + /* Trim or similar currently pending completion */ +#define CAM_IOSCHED_FLAG_TRIM_ACTIVE (1ul << 0) + /* Callout active, and needs to be torn down */ +#define CAM_IOSCHED_FLAG_CALLOUT_ACTIVE (1ul << 1) + + /* Periph drivers set these flags to indicate work */ +#define CAM_IOSCHED_FLAG_WORK_FLAGS ((0xffffu) << 16) + +static void +cam_iosched_io_metric_update(struct cam_iosched_softc *isc, + sbintime_t sim_latency, int cmd, size_t size); + +static inline int +cam_iosched_has_flagged_work(struct cam_iosched_softc *isc) +{ + return !!(isc->flags & CAM_IOSCHED_FLAG_WORK_FLAGS); +} + +static inline int +cam_iosched_has_io(struct cam_iosched_softc *isc) +{ +#ifdef CAM_NETFLIX_IOSCHED + if (do_netflix_iosched) { + struct bio *rbp = bioq_first(&isc->bio_queue); + struct bio *wbp = bioq_first(&isc->write_queue); + int can_write = wbp != NULL && + cam_iosched_limiter_caniop(&isc->write_stats, wbp) == 0; + int can_read = rbp != NULL && + cam_iosched_limiter_caniop(&isc->read_stats, rbp) == 0; + if (iosched_debug > 2) { + printf("can write %d: pending_writes %d max_writes %d\n", can_write, isc->write_stats.pending, isc->write_stats.max); + printf("can read %d: read_stats.pending %d max_reads %d\n", can_read, isc->read_stats.pending, isc->read_stats.max); + printf("Queued reads %d writes %d\n", isc->read_stats.queued, isc->write_stats.queued); + } + return can_read || can_write; + } +#endif + return bioq_first(&isc->bio_queue) != NULL; +} + +static inline int +cam_iosched_has_more_trim(struct cam_iosched_softc *isc) +{ + return !(isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) && + bioq_first(&isc->trim_queue); +} + +#define cam_iosched_sort_queue(isc) ((isc)->sort_io_queue >= 0 ? \ + (isc)->sort_io_queue : cam_sort_io_queues) + + +static inline int +cam_iosched_has_work(struct cam_iosched_softc *isc) +{ +#ifdef CAM_NETFLIX_IOSCHED + if (iosched_debug > 2) + printf("has work: %d %d %d\n", cam_iosched_has_io(isc), + cam_iosched_has_more_trim(isc), + cam_iosched_has_flagged_work(isc)); +#endif + + return cam_iosched_has_io(isc) || + cam_iosched_has_more_trim(isc) || + cam_iosched_has_flagged_work(isc); +} + +#ifdef CAM_NETFLIX_IOSCHED +static void +cam_iosched_iop_stats_init(struct cam_iosched_softc *isc, struct iop_stats *ios) +{ + + ios->limiter = none; + cam_iosched_limiter_init(ios); + ios->in = 0; + ios->max = 300000; + ios->min = 1; + ios->out = 0; + ios->pending = 0; + ios->queued = 0; + ios->total = 0; + ios->ema = 0; + ios->emss = 0; + ios->sd = 0; + ios->softc = isc; +} + +static int +cam_iosched_limiter_sysctl(SYSCTL_HANDLER_ARGS) +{ + char buf[16]; + struct iop_stats *ios; + struct cam_iosched_softc *isc; + int value, i, error, cantick; + const char *p; + + ios = arg1; + isc = ios->softc; + value = ios->limiter; + if (value < none || value >= limiter_max) + p = "UNKNOWN"; + else + p = cam_iosched_limiter_names[value]; + + strlcpy(buf, p, sizeof(buf)); + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error != 0 || req->newptr == NULL) + return error; + + cam_periph_lock(isc->periph); + + for (i = none; i < limiter_max; i++) { + if (strcmp(buf, cam_iosched_limiter_names[i]) != 0) + continue; + ios->limiter = i; + error = cam_iosched_limiter_init(ios); + if (error != 0) { + ios->limiter = value; + cam_periph_unlock(isc->periph); + return error; + } + cantick = !!limsw[isc->read_stats.limiter].l_tick + + !!limsw[isc->write_stats.limiter].l_tick + + !!limsw[isc->trim_stats.limiter].l_tick + + 1; /* Control loop requires it */ + if (isc->flags & CAM_IOSCHED_FLAG_CALLOUT_ACTIVE) { + if (cantick == 0) { + callout_stop(&isc->ticker); + isc->flags &= ~CAM_IOSCHED_FLAG_CALLOUT_ACTIVE; + } + } else { + if (cantick != 0) { + callout_reset(&isc->ticker, hz / isc->quanta - 1, cam_iosched_ticker, isc); + isc->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE; + } + } + + cam_periph_unlock(isc->periph); + return 0; + } + + cam_periph_unlock(isc->periph); + return EINVAL; +} + +static int +cam_iosched_control_type_sysctl(SYSCTL_HANDLER_ARGS) +{ + char buf[16]; + struct control_loop *clp; + struct cam_iosched_softc *isc; + int value, i, error; + const char *p; + + clp = arg1; + isc = clp->softc; + value = clp->type; + if (value < none || value >= cl_max) + p = "UNKNOWN"; + else + p = cam_iosched_control_type_names[value]; + + strlcpy(buf, p, sizeof(buf)); + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error != 0 || req->newptr == NULL) + return error; + + for (i = set_max; i < cl_max; i++) { + if (strcmp(buf, cam_iosched_control_type_names[i]) != 0) + continue; + cam_periph_lock(isc->periph); + clp->type = i; + cam_periph_unlock(isc->periph); + return 0; + } + + return EINVAL; +} + +static int +cam_iosched_sbintime_sysctl(SYSCTL_HANDLER_ARGS) +{ + char buf[16]; + sbintime_t value; + int error; + uint64_t us; + + value = *(sbintime_t *)arg1; + us = (uint64_t)value / SBT_1US; + snprintf(buf, sizeof(buf), "%ju", (intmax_t)us); + error = sysctl_handle_string(oidp, buf, sizeof(buf), req); + if (error != 0 || req->newptr == NULL) + return error; + us = strtoul(buf, NULL, 10); + if (us == 0) + return EINVAL; + *(sbintime_t *)arg1 = us * SBT_1US; + return 0; +} + +static void +cam_iosched_iop_stats_sysctl_init(struct cam_iosched_softc *isc, struct iop_stats *ios, char *name) +{ + struct sysctl_oid_list *n; + struct sysctl_ctx_list *ctx; + + ios->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx, + SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, name, + CTLFLAG_RD, 0, name); + n = SYSCTL_CHILDREN(ios->sysctl_tree); + ctx = &ios->sysctl_ctx; + + SYSCTL_ADD_UQUAD(ctx, n, + OID_AUTO, "ema", CTLFLAG_RD, + &ios->ema, + "Fast Exponentially Weighted Moving Average"); + SYSCTL_ADD_UQUAD(ctx, n, + OID_AUTO, "emss", CTLFLAG_RD, + &ios->emss, + "Fast Exponentially Weighted Moving Sum of Squares (maybe wrong)"); + SYSCTL_ADD_UQUAD(ctx, n, + OID_AUTO, "sd", CTLFLAG_RD, + &ios->sd, + "Estimated SD for fast ema (may be wrong)"); + + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "pending", CTLFLAG_RD, + &ios->pending, 0, + "Instantaneous # of pending transactions"); + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "count", CTLFLAG_RD, + &ios->total, 0, + "# of transactions submitted to hardware"); + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "queued", CTLFLAG_RD, + &ios->queued, 0, + "# of transactions in the queue"); + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "in", CTLFLAG_RD, + &ios->in, 0, + "# of transactions queued to driver"); + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "out", CTLFLAG_RD, + &ios->out, 0, + "# of transactions completed"); + + SYSCTL_ADD_PROC(ctx, n, + OID_AUTO, "limiter", CTLTYPE_STRING | CTLFLAG_RW, + ios, 0, cam_iosched_limiter_sysctl, "A", + "Current limiting type."); + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "min", CTLFLAG_RW, + &ios->min, 0, + "min resource"); + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "max", CTLFLAG_RW, + &ios->max, 0, + "max resource"); + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "current", CTLFLAG_RW, + &ios->current, 0, + "current resource"); + +} + +static void +cam_iosched_iop_stats_fini(struct iop_stats *ios) +{ + if (ios->sysctl_tree) + if (sysctl_ctx_free(&ios->sysctl_ctx) != 0) + printf("can't remove iosched sysctl stats context\n"); +} + +static void +cam_iosched_cl_sysctl_init(struct cam_iosched_softc *isc) +{ + struct sysctl_oid_list *n; + struct sysctl_ctx_list *ctx; + struct control_loop *clp; + + clp = &isc->cl; + clp->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx, + SYSCTL_CHILDREN(isc->sysctl_tree), OID_AUTO, "control", + CTLFLAG_RD, 0, "Control loop info"); + n = SYSCTL_CHILDREN(clp->sysctl_tree); + ctx = &clp->sysctl_ctx; + + SYSCTL_ADD_PROC(ctx, n, + OID_AUTO, "type", CTLTYPE_STRING | CTLFLAG_RW, + clp, 0, cam_iosched_control_type_sysctl, "A", + "Control loop algorithm"); + SYSCTL_ADD_PROC(ctx, n, + OID_AUTO, "steer_interval", CTLTYPE_STRING | CTLFLAG_RW, + &clp->steer_interval, 0, cam_iosched_sbintime_sysctl, "A", + "How often to steer (in us)"); + SYSCTL_ADD_PROC(ctx, n, + OID_AUTO, "lolat", CTLTYPE_STRING | CTLFLAG_RW, + &clp->lolat, 0, cam_iosched_sbintime_sysctl, "A", + "Low water mark for Latency (in us)"); + SYSCTL_ADD_PROC(ctx, n, + OID_AUTO, "hilat", CTLTYPE_STRING | CTLFLAG_RW, + &clp->hilat, 0, cam_iosched_sbintime_sysctl, "A", + "Hi water mark for Latency (in us)"); + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "alpha", CTLFLAG_RW, + &clp->alpha, 0, + "Alpha for PLL (x100) aka gain"); +} + +static void +cam_iosched_cl_sysctl_fini(struct control_loop *clp) +{ + if (clp->sysctl_tree) + if (sysctl_ctx_free(&clp->sysctl_ctx) != 0) + printf("can't remove iosched sysctl control loop context\n"); +} +#endif + +/* + * Allocate the iosched structure. This also insulates callers from knowing + * sizeof struct cam_iosched_softc. + */ +int +cam_iosched_init(struct cam_iosched_softc **iscp, struct cam_periph *periph) +{ + + *iscp = malloc(sizeof(**iscp), M_CAMSCHED, M_NOWAIT | M_ZERO); + if (*iscp == NULL) + return ENOMEM; +#ifdef CAM_NETFLIX_IOSCHED + if (iosched_debug) + printf("CAM IOSCHEDULER Allocating entry at %p\n", *iscp); +#endif + (*iscp)->sort_io_queue = -1; + bioq_init(&(*iscp)->bio_queue); + bioq_init(&(*iscp)->trim_queue); +#ifdef CAM_NETFLIX_IOSCHED + if (do_netflix_iosched) { + bioq_init(&(*iscp)->write_queue); + (*iscp)->read_bias = 100; + (*iscp)->current_read_bias = 100; + (*iscp)->quanta = 200; + cam_iosched_iop_stats_init(*iscp, &(*iscp)->read_stats); + cam_iosched_iop_stats_init(*iscp, &(*iscp)->write_stats); + cam_iosched_iop_stats_init(*iscp, &(*iscp)->trim_stats); + (*iscp)->trim_stats.max = 1; /* Trims are special: one at a time for now */ + (*iscp)->last_time = sbinuptime(); + callout_init_mtx(&(*iscp)->ticker, cam_periph_mtx(periph), 0); + (*iscp)->periph = periph; + cam_iosched_cl_init(&(*iscp)->cl, *iscp); + callout_reset(&(*iscp)->ticker, hz / (*iscp)->quanta - 1, cam_iosched_ticker, *iscp); + (*iscp)->flags |= CAM_IOSCHED_FLAG_CALLOUT_ACTIVE; + } +#endif + + return 0; +} + +/* + * Reclaim all used resources. This assumes that other folks have + * drained the requests in the hardware. Maybe an unwise assumption. + */ +void +cam_iosched_fini(struct cam_iosched_softc *isc) +{ + if (isc) { + cam_iosched_flush(isc, NULL, ENXIO); +#ifdef CAM_NETFLIX_IOSCHED + cam_iosched_iop_stats_fini(&isc->read_stats); + cam_iosched_iop_stats_fini(&isc->write_stats); + cam_iosched_iop_stats_fini(&isc->trim_stats); + cam_iosched_cl_sysctl_fini(&isc->cl); + if (isc->sysctl_tree) + if (sysctl_ctx_free(&isc->sysctl_ctx) != 0) + printf("can't remove iosched sysctl stats context\n"); + if (isc->flags & CAM_IOSCHED_FLAG_CALLOUT_ACTIVE) { + callout_drain(&isc->ticker); + isc->flags &= ~ CAM_IOSCHED_FLAG_CALLOUT_ACTIVE; + } + +#endif + free(isc, M_CAMSCHED); + } +} + +/* + * After we're sure we're attaching a device, go ahead and add + * hooks for any sysctl we may wish to honor. + */ +void cam_iosched_sysctl_init(struct cam_iosched_softc *isc, + struct sysctl_ctx_list *ctx, struct sysctl_oid *node) +{ +#ifdef CAM_NETFLIX_IOSCHED + struct sysctl_oid_list *n; +#endif + + SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(node), + OID_AUTO, "sort_io_queue", CTLFLAG_RW | CTLFLAG_MPSAFE, + &isc->sort_io_queue, 0, + "Sort IO queue to try and optimise disk access patterns"); + +#ifdef CAM_NETFLIX_IOSCHED + if (!do_netflix_iosched) + return; + + isc->sysctl_tree = SYSCTL_ADD_NODE(&isc->sysctl_ctx, + SYSCTL_CHILDREN(node), OID_AUTO, "iosched", + CTLFLAG_RD, 0, "I/O scheduler statistics"); + n = SYSCTL_CHILDREN(isc->sysctl_tree); + ctx = &isc->sysctl_ctx; + + cam_iosched_iop_stats_sysctl_init(isc, &isc->read_stats, "read"); + cam_iosched_iop_stats_sysctl_init(isc, &isc->write_stats, "write"); + cam_iosched_iop_stats_sysctl_init(isc, &isc->trim_stats, "trim"); + cam_iosched_cl_sysctl_init(isc); + + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "read_bias", CTLFLAG_RW, + &isc->read_bias, 100, + "How biased towards read should we be independent of limits"); + + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "quanta", CTLFLAG_RW, + &isc->quanta, 200, + "How many quanta per second do we slice the I/O up into"); + + SYSCTL_ADD_INT(ctx, n, + OID_AUTO, "total_ticks", CTLFLAG_RD, + &isc->total_ticks, 0, + "Total number of ticks we've done"); +#endif +} + +/* + * Flush outstanding I/O. Consumers of this library don't know all the + * queues we may keep, so this allows all I/O to be flushed in one + * convenient call. + */ +void +cam_iosched_flush(struct cam_iosched_softc *isc, struct devstat *stp, int err) +{ + bioq_flush(&isc->bio_queue, stp, err); + bioq_flush(&isc->trim_queue, stp, err); +#ifdef CAM_NETFLIX_IOSCHED + if (do_netflix_iosched) + bioq_flush(&isc->write_queue, stp, err); +#endif +} + +#ifdef CAM_NETFLIX_IOSCHED +static struct bio * +cam_iosched_get_write(struct cam_iosched_softc *isc) +{ + struct bio *bp; + + /* + * We control the write rate by controlling how many requests we send + * down to the drive at any one time. Fewer requests limits the + * effects of both starvation when the requests take a while and write + * amplification when each request is causing more than one write to + * the NAND media. Limiting the queue depth like this will also limit + * the write throughput and give and reads that want to compete to + * compete unfairly. + */ + bp = bioq_first(&isc->write_queue); + if (bp == NULL) { + if (iosched_debug > 3) + printf("No writes present in write_queue\n"); + return NULL; + } + + /* + * If pending read, prefer that based on current read bias + * setting. + */ + if (bioq_first(&isc->bio_queue) && isc->current_read_bias) { + if (iosched_debug) + printf("Reads present and current_read_bias is %d queued writes %d queued reads %d\n", isc->current_read_bias, isc->write_stats.queued, isc->read_stats.queued); + isc->current_read_bias--; + return NULL; + } + + /* + * See if our current limiter allows this I/O. + */ + if (cam_iosched_limiter_iop(&isc->write_stats, bp) != 0) { + if (iosched_debug) + printf("Can't write because limiter says no.\n"); + return NULL; + } + + /* + * Let's do this: We've passed all the gates and we're a go + * to schedule the I/O in the SIM. + */ + isc->current_read_bias = isc->read_bias; + bioq_remove(&isc->write_queue, bp); + if (bp->bio_cmd == BIO_WRITE) { + isc->write_stats.queued--; + isc->write_stats.total++; + isc->write_stats.pending++; + } + if (iosched_debug > 9) + printf("HWQ : %p %#x\n", bp, bp->bio_cmd); + return bp; +} +#endif + +/* + * Put back a trim that you weren't able to actually schedule this time. + */ +void +cam_iosched_put_back_trim(struct cam_iosched_softc *isc, struct bio *bp) +{ + bioq_insert_head(&isc->trim_queue, bp); +#ifdef CAM_NETFLIX_IOSCHED + isc->trim_stats.queued++; + isc->trim_stats.total--; /* since we put it back, don't double count */ + isc->trim_stats.pending--; +#endif +} + +/* + * gets the next trim from the trim queue. + * + * Assumes we're called with the periph lock held. It removes this + * trim from the queue and the device must explicitly reinstert it + * should the need arise. + */ +struct bio * +cam_iosched_next_trim(struct cam_iosched_softc *isc) +{ + struct bio *bp; + + bp = bioq_first(&isc->trim_queue); + if (bp == NULL) + return NULL; + bioq_remove(&isc->trim_queue, bp); +#ifdef CAM_NETFLIX_IOSCHED + isc->trim_stats.queued--; + isc->trim_stats.total++; + isc->trim_stats.pending++; +#endif + return bp; +} + +/* + * gets the an available trim from the trim queue, if there's no trim + * already pending. It removes this trim from the queue and the device + * must explicitly reinstert it should the need arise. + * + * Assumes we're called with the periph lock held. + */ +struct bio * +cam_iosched_get_trim(struct cam_iosched_softc *isc) +{ + + if (!cam_iosched_has_more_trim(isc)) + return NULL; + + return cam_iosched_next_trim(isc); +} + +/* + * Determine what the next bit of work to do is for the periph. The + * default implementation looks to see if we have trims to do, but no + * trims outstanding. If so, we do that. Otherwise we see if we have + * other work. If we do, then we do that. Otherwise why were we called? + */ +struct bio * +cam_iosched_next_bio(struct cam_iosched_softc *isc) +{ + struct bio *bp; + + /* + * See if we have a trim that can be scheduled. We can only send one + * at a time down, so this takes that into account. + * + * XXX newer TRIM commands are queueable. Revisit this when we + * implement them. + */ + if ((bp = cam_iosched_get_trim(isc)) != NULL) + return bp; + +#ifdef CAM_NETFLIX_IOSCHED + /* + * See if we have any pending writes, and room in the queue for them, + * and if so, those are next. + */ + if (do_netflix_iosched) { + if ((bp = cam_iosched_get_write(isc)) != NULL) + return bp; + } +#endif + + /* + * next, see if there's other, normal I/O waiting. If so return that. + */ + if ((bp = bioq_first(&isc->bio_queue)) == NULL) + return NULL; + +#ifdef CAM_NETFLIX_IOSCHED + /* + * For the netflix scheduler, bio_queue is only for reads, so enforce + * the limits here. Enforce only for reads. + */ + if (do_netflix_iosched) { + if (bp->bio_cmd == BIO_READ && + cam_iosched_limiter_iop(&isc->read_stats, bp) != 0) + return NULL; + } +#endif + bioq_remove(&isc->bio_queue, bp); +#ifdef CAM_NETFLIX_IOSCHED + if (do_netflix_iosched) { + if (bp->bio_cmd == BIO_READ) { + isc->read_stats.queued--; + isc->read_stats.total++; + isc->read_stats.pending++; + } else + printf("Found bio_cmd = %#x\n", bp->bio_cmd); + } + if (iosched_debug > 9) + printf("HWQ : %p %#x\n", bp, bp->bio_cmd); +#endif + return bp; +} + +/* + * Driver has been given some work to do by the block layer. Tell the + * scheduler about it and have it queue the work up. The scheduler module + * will then return the currently most useful bit of work later, possibly + * deferring work for various reasons. + */ +void +cam_iosched_queue_work(struct cam_iosched_softc *isc, struct bio *bp) +{ + + /* + * Put all trims on the trim queue sorted, since we know + * that the collapsing code requires this. Otherwise put + * the work on the bio queue. + */ + if (bp->bio_cmd == BIO_DELETE) { + bioq_disksort(&isc->trim_queue, bp); +#ifdef CAM_NETFLIX_IOSCHED + isc->trim_stats.in++; + isc->trim_stats.queued++; +#endif + } +#ifdef CAM_NETFLIX_IOSCHED + else if (do_netflix_iosched && + (bp->bio_cmd == BIO_WRITE || bp->bio_cmd == BIO_FLUSH)) { + if (cam_iosched_sort_queue(isc)) + bioq_disksort(&isc->write_queue, bp); + else + bioq_insert_tail(&isc->write_queue, bp); + if (iosched_debug > 9) + printf("Qw : %p %#x\n", bp, bp->bio_cmd); + if (bp->bio_cmd == BIO_WRITE) { + isc->write_stats.in++; + isc->write_stats.queued++; + } + } +#endif + else { + if (cam_iosched_sort_queue(isc)) + bioq_disksort(&isc->bio_queue, bp); + else + bioq_insert_tail(&isc->bio_queue, bp); +#ifdef CAM_NETFLIX_IOSCHED + if (iosched_debug > 9) + printf("Qr : %p %#x\n", bp, bp->bio_cmd); + if (bp->bio_cmd == BIO_READ) { + isc->read_stats.in++; + isc->read_stats.queued++; + } else if (bp->bio_cmd == BIO_WRITE) { + isc->write_stats.in++; + isc->write_stats.queued++; + } +#endif + } +} + +/* + * If we have work, get it scheduled. Called with the periph lock held. + */ +void +cam_iosched_schedule(struct cam_iosched_softc *isc, struct cam_periph *periph) +{ + + if (cam_iosched_has_work(isc)) + xpt_schedule(periph, CAM_PRIORITY_NORMAL); +} + +/* + * Complete a trim request + */ +void +cam_iosched_trim_done(struct cam_iosched_softc *isc) +{ + + isc->flags &= ~CAM_IOSCHED_FLAG_TRIM_ACTIVE; +} + +/* + * Complete a bio. Called before we release the ccb with xpt_release_ccb so we + * might use notes in the ccb for statistics. + */ +int +cam_iosched_bio_complete(struct cam_iosched_softc *isc, struct bio *bp, + union ccb *done_ccb) +{ + int retval = 0; +#ifdef CAM_NETFLIX_IOSCHED + if (!do_netflix_iosched) + return retval; + + if (iosched_debug > 10) + printf("done: %p %#x\n", bp, bp->bio_cmd); + if (bp->bio_cmd == BIO_WRITE) { + retval = cam_iosched_limiter_iodone(&isc->write_stats, bp); + isc->write_stats.out++; + isc->write_stats.pending--; + } else if (bp->bio_cmd == BIO_READ) { + retval = cam_iosched_limiter_iodone(&isc->read_stats, bp); + isc->read_stats.out++; + isc->read_stats.pending--; + } else if (bp->bio_cmd == BIO_DELETE) { + isc->trim_stats.out++; + isc->trim_stats.pending--; + } else if (bp->bio_cmd != BIO_FLUSH) { + if (iosched_debug) + printf("Completing command with bio_cmd == %#x\n", bp->bio_cmd); + } + + if (!(bp->bio_flags & BIO_ERROR)) + cam_iosched_io_metric_update(isc, done_ccb->ccb_h.qos.sim_data, + bp->bio_cmd, bp->bio_bcount); +#endif + return retval; +} + +/* + * Tell the io scheduler that you've pushed a trim down into the sim. + * xxx better place for this? + */ +void +cam_iosched_submit_trim(struct cam_iosched_softc *isc) +{ + + isc->flags |= CAM_IOSCHED_FLAG_TRIM_ACTIVE; +} + +/* + * Change the sorting policy hint for I/O transactions for this device. + */ +void +cam_iosched_set_sort_queue(struct cam_iosched_softc *isc, int val) +{ + + isc->sort_io_queue = val; +} + +int +cam_iosched_has_work_flags(struct cam_iosched_softc *isc, uint32_t flags) +{ + return isc->flags & flags; +} + +void +cam_iosched_set_work_flags(struct cam_iosched_softc *isc, uint32_t flags) +{ + isc->flags |= flags; +} + +void +cam_iosched_clr_work_flags(struct cam_iosched_softc *isc, uint32_t flags) +{ + isc->flags &= ~flags; +} + +#ifdef CAM_NETFLIX_IOSCHED +/* + * After the method presented in Jack Crenshaw's 1998 article "Integer + * Suqare Roots," reprinted at + * http://www.embedded.com/electronics-blogs/programmer-s-toolbox/4219659/Integer-Square-Roots + * and well worth the read. Briefly, we find the power of 4 that's the + * largest smaller than val. We then check each smaller power of 4 to + * see if val is still bigger. The right shifts at each step divide + * the result by 2 which after successive application winds up + * accumulating the right answer. It could also have been accumulated + * using a separate root counter, but this code is smaller and faster + * than that method. This method is also integer size invariant. + * It returns floor(sqrt((float)val)), or the larget integer less than + * or equal to the square root. + */ +static uint64_t +isqrt64(uint64_t val) +{ + uint64_t res = 0; + uint64_t bit = 1ULL << (sizeof(uint64_t) * NBBY - 2); + + /* + * Find the largest power of 4 smaller than val. + */ + while (bit > val) + bit >>= 2; + + /* + * Accumulate the answer, one bit at a time (we keep moving + * them over since 2 is the square root of 4 and we test + * powers of 4). We accumulate where we find the bit, but + * the successive shifts land the bit in the right place + * by the end. + */ + while (bit != 0) { + if (val >= res + bit) { + val -= res + bit; + res = (res >> 1) + bit; + } else + res >>= 1; + bit >>= 2; + } + + return res; +} + +/* + * a and b are 32.32 fixed point stored in a 64-bit word. + * Let al and bl be the .32 part of a and b. + * Let ah and bh be the 32 part of a and b. + * R is the radix and is 1 << 32 + * + * a * b + * (ah + al / R) * (bh + bl / R) + * ah * bh + (al * bh + ah * bl) / R + al * bl / R^2 + * + * After multiplicaiton, we have to renormalize by multiply by + * R, so we wind up with + * ah * bh * R + al * bh + ah * bl + al * bl / R + * which turns out to be a very nice way to compute this value + * so long as ah and bh are < 65536 there's no loss of high bits + * and the low order bits are below the threshold of caring for + * this application. + */ +static uint64_t +mul(uint64_t a, uint64_t b) +{ + uint64_t al, ah, bl, bh; + al = a & 0xffffffff; + ah = a >> 32; + bl = b & 0xffffffff; + bh = b >> 32; + return ((ah * bh) << 32) + al * bh + ah * bl + ((al * bl) >> 32); +} + +static void +cam_iosched_update(struct iop_stats *iop, sbintime_t sim_latency) +{ + sbintime_t y, yy; + uint64_t var; + + /* + * Classic expoentially decaying average with a tiny alpha + * (2 ^ -alpha_bits). For more info see the NIST statistical + * handbook. + * + * ema_t = y_t * alpha + ema_t-1 * (1 - alpha) + * alpha = 1 / (1 << alpha_bits) + * + * Since alpha is a power of two, we can compute this w/o any mult or + * division. + */ + y = sim_latency; + iop->ema = (y + (iop->ema << alpha_bits) - iop->ema) >> alpha_bits; + + yy = mul(y, y); + iop->emss = (yy + (iop->emss << alpha_bits) - iop->emss) >> alpha_bits; + + /* + * s_1 = sum of data + * s_2 = sum of data * data + * ema ~ mean (or s_1 / N) + * emss ~ s_2 / N + * + * sd = sqrt((N * s_2 - s_1 ^ 2) / (N * (N - 1))) + * sd = sqrt((N * s_2 / N * (N - 1)) - (s_1 ^ 2 / (N * (N - 1)))) + * + * N ~ 2 / alpha - 1 + * alpha < 1 / 16 (typically much less) + * N > 31 --> N large so N * (N - 1) is approx N * N + * + * substituting and rearranging: + * sd ~ sqrt(s_2 / N - (s_1 / N) ^ 2) + * ~ sqrt(emss - ema ^ 2); + * which is the formula used here to get a decent estimate of sd which + * we use to detect outliers. Note that when first starting up, it + * takes a while for emss sum of squares estimator to converge on a + * good value. during this time, it can be less than ema^2. We + * compute a sd of 0 in that case, and ignore outliers. + */ + var = iop->emss - mul(iop->ema, iop->ema); + iop->sd = (int64_t)var < 0 ? 0 : isqrt64(var); +} + +static void +cam_iosched_io_metric_update(struct cam_iosched_softc *isc, + sbintime_t sim_latency, int cmd, size_t size) +{ + /* xxx Do we need to scale based on the size of the I/O ? */ + switch (cmd) { + case BIO_READ: + cam_iosched_update(&isc->read_stats, sim_latency); + break; + case BIO_WRITE: + cam_iosched_update(&isc->write_stats, sim_latency); + break; + case BIO_DELETE: + cam_iosched_update(&isc->trim_stats, sim_latency); + break; + default: + break; + } +} + +#ifdef DDB +static int biolen(struct bio_queue_head *bq) +{ + int i = 0; + struct bio *bp; + + TAILQ_FOREACH(bp, &bq->queue, bio_queue) { + i++; + } + return i; +} + +/* + * Show the internal state of the I/O scheduler. + */ +DB_SHOW_COMMAND(iosched, cam_iosched_db_show) +{ + struct cam_iosched_softc *isc; + + if (!have_addr) { + db_printf("Need addr\n"); + return; + } + isc = (struct cam_iosched_softc *)addr; + db_printf("pending_reads: %d\n", isc->read_stats.pending); + db_printf("min_reads: %d\n", isc->read_stats.min); + db_printf("max_reads: %d\n", isc->read_stats.max); + db_printf("reads: %d\n", isc->read_stats.total); + db_printf("in_reads: %d\n", isc->read_stats.in); + db_printf("out_reads: %d\n", isc->read_stats.out); + db_printf("queued_reads: %d\n", isc->read_stats.queued); + db_printf("Current Q len %d\n", biolen(&isc->bio_queue)); + db_printf("pending_writes: %d\n", isc->write_stats.pending); + db_printf("min_writes: %d\n", isc->write_stats.min); + db_printf("max_writes: %d\n", isc->write_stats.max); + db_printf("writes: %d\n", isc->write_stats.total); + db_printf("in_writes: %d\n", isc->write_stats.in); + db_printf("out_writes: %d\n", isc->write_stats.out); + db_printf("queued_writes: %d\n", isc->write_stats.queued); + db_printf("Current Q len %d\n", biolen(&isc->write_queue)); + db_printf("pending_trims: %d\n", isc->trim_stats.pending); + db_printf("min_trims: %d\n", isc->trim_stats.min); + db_printf("max_trims: %d\n", isc->trim_stats.max); + db_printf("trims: %d\n", isc->trim_stats.total); + db_printf("in_trims: %d\n", isc->trim_stats.in); + db_printf("out_trims: %d\n", isc->trim_stats.out); + db_printf("queued_trims: %d\n", isc->trim_stats.queued); + db_printf("Current Q len %d\n", biolen(&isc->trim_queue)); + db_printf("read_bias: %d\n", isc->read_bias); + db_printf("current_read_bias: %d\n", isc->current_read_bias); + db_printf("Trim active? %s\n", + (isc->flags & CAM_IOSCHED_FLAG_TRIM_ACTIVE) ? "yes" : "no"); +} +#endif +#endif diff --git a/sys/cam/cam_iosched.h b/sys/cam/cam_iosched.h new file mode 100644 index 000000000000..34c926d8d4ae --- /dev/null +++ b/sys/cam/cam_iosched.h @@ -0,0 +1,64 @@ +/*- + * CAM IO Scheduler Interface + * + * Copyright (c) 2015 Netflix, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer, + * without modification, immediately at the beginning of the file. + * 2. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * $FreeBSD$ + */ + +#ifndef _CAM_CAM_IOSCHED_H +#define _CAM_CAM_IOSCHED_H + +/* No user-servicable parts in here. */ +#ifdef _KERNEL + +/* Forward declare all structs to keep interface thin */ +struct cam_iosched_softc; +struct sysctl_ctx_list; +struct sysctl_oid; +union ccb; +struct bio; + +int cam_iosched_init(struct cam_iosched_softc **, struct cam_periph *periph); +void cam_iosched_fini(struct cam_iosched_softc *); +void cam_iosched_sysctl_init(struct cam_iosched_softc *, struct sysctl_ctx_list *, struct sysctl_oid *); +struct bio *cam_iosched_next_trim(struct cam_iosched_softc *isc); +struct bio *cam_iosched_get_trim(struct cam_iosched_softc *isc); +struct bio *cam_iosched_next_bio(struct cam_iosched_softc *isc); +void cam_iosched_queue_work(struct cam_iosched_softc *isc, struct bio *bp); +void cam_iosched_flush(struct cam_iosched_softc *isc, struct devstat *stp, int err); +void cam_iosched_schedule(struct cam_iosched_softc *isc, struct cam_periph *periph); +void cam_iosched_finish_trim(struct cam_iosched_softc *isc); +void cam_iosched_submit_trim(struct cam_iosched_softc *isc); +void cam_iosched_put_back_trim(struct cam_iosched_softc *isc, struct bio *bp); +void cam_iosched_set_sort_queue(struct cam_iosched_softc *isc, int val); +int cam_iosched_has_work_flags(struct cam_iosched_softc *isc, uint32_t flags); +void cam_iosched_set_work_flags(struct cam_iosched_softc *isc, uint32_t flags); +void cam_iosched_clr_work_flags(struct cam_iosched_softc *isc, uint32_t flags); +void cam_iosched_trim_done(struct cam_iosched_softc *isc); +int cam_iosched_bio_complete(struct cam_iosched_softc *isc, struct bio *bp, union ccb *done_ccb); + +#endif +#endif From 86ddf15ebda20495e019d15b0cd1bbea0eb00cbe Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Thu, 14 Apr 2016 22:13:46 +0000 Subject: [PATCH 071/143] Add a comment about why the timeout for flush was lowered to 5s. --- sys/cam/ata/ata_da.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sys/cam/ata/ata_da.c b/sys/cam/ata/ata_da.c index 3d3afbd73dd3..1d1d033c6833 100644 --- a/sys/cam/ata/ata_da.c +++ b/sys/cam/ata/ata_da.c @@ -912,6 +912,11 @@ adadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t len if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) { xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL); + /* + * Tell the drive to flush its intenral cache. if we + * can't flush in 5s we have big problems. No need to + * wait the default 60s to detect problems. + */ ccb.ccb_h.ccb_state = ADA_CCB_DUMP; cam_fill_ataio(&ccb.ataio, 0, From 423e350b31c80065e909b0942b58474870129cdc Mon Sep 17 00:00:00 2001 From: Enji Cooper Date: Thu, 14 Apr 2016 22:22:03 +0000 Subject: [PATCH 072/143] Add DEBUG_FLAGS to PROG_VARS and STRIP to PROG_OVERRIDE_VARS This will allow the variables [*] to be overridden on a per-PROG basis, which is useful when controlling "stripping" behavior for some tests that require debug symbols or to be unstripped DEBUG_FLAGS (similar to CFLAGS) supports appending, whereas STRIP is an override *: Due to how STRIP is defined in bsd.own.mk (in addition to bsd.lib.mk and bsd.prog.mk), and the fact that bsd.test.mk pulls in bsd.own.mk first, overriding STRIP doesn't work today. A follow up commit is pending to "rectify" this after additional testing is done. Discussed with: bdrewery MFC after: 1 week Sponsored by: EMC / Isilon Storage Division --- share/mk/bsd.progs.mk | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/share/mk/bsd.progs.mk b/share/mk/bsd.progs.mk index 00dd5663fab9..d26ba76f85e3 100644 --- a/share/mk/bsd.progs.mk +++ b/share/mk/bsd.progs.mk @@ -23,8 +23,8 @@ PROGS += ${PROGS_CXX} .if defined(PROG) # just one of many PROG_OVERRIDE_VARS += BINDIR BINGRP BINOWN BINMODE DPSRCS MAN NO_WERROR \ - PROGNAME SRCS WARNS -PROG_VARS += CFLAGS CXXFLAGS DPADD LDADD LIBADD LINKS \ + PROGNAME SRCS STRIP WARNS +PROG_VARS += CFLAGS CXXFLAGS DEBUG_FLAGS DPADD LDADD LIBADD LINKS \ LDFLAGS MLINKS ${PROG_OVERRIDE_VARS} .for v in ${PROG_VARS:O:u} .if empty(${PROG_OVERRIDE_VARS:M$v}) From 84833cfe3953ee955a85fa5248def4345b7ab096 Mon Sep 17 00:00:00 2001 From: Enji Cooper Date: Thu, 14 Apr 2016 22:23:15 +0000 Subject: [PATCH 073/143] Commit documentation change for r298012 Requested by: bdrewery X-MFC with: r298012 Sponsored by: EMC / Isilon Storage Division --- share/mk/bsd.README | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/share/mk/bsd.README b/share/mk/bsd.README index bda9a8c1a3bc..1328e24cfb2c 100644 --- a/share/mk/bsd.README +++ b/share/mk/bsd.README @@ -315,8 +315,8 @@ PROGS_CXX PROG and PROGS_CXX in one Makefile. To define SRCS.bar= bar_src.c The supported variables are BINDIR BINGRP BINMODE BINOWN - CFLAGS CXXFLAGS DPADD DPSRCS LDADD - LDFLAGS LIBADD MAN MLINKS PROGNAME SRCS. + CFLAGS CXXFLAGS DEBUG_FLAGS DPADD DPSRCS LDADD + LDFLAGS LIBADD MAN MLINKS PROGNAME SRCS STRIP. PROGNAME The name that the above program will be installed as, if different from ${PROG}. From 206c31c8121463c8f5983983e5f5560590caca99 Mon Sep 17 00:00:00 2001 From: Enji Cooper Date: Thu, 14 Apr 2016 22:32:56 +0000 Subject: [PATCH 074/143] Regenerate the list of bsd.progs.mk supported variables Prefix with dashes (unordered list) and put one variable on each line (to avoid future conflicts) Done via the following one-liner: > sh -c 'for i in $(make -C tests/sys/aio PROG=foo -VPROG_VARS:O); do printf "\t\t- $i\n"; done' MFC after: 1 week Sponsored by: EMC / Isilon Storage Division --- share/mk/bsd.README | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/share/mk/bsd.README b/share/mk/bsd.README index 1328e24cfb2c..b0719593f6d8 100644 --- a/share/mk/bsd.README +++ b/share/mk/bsd.README @@ -314,9 +314,27 @@ PROGS_CXX PROG and PROGS_CXX in one Makefile. To define LDADD.foo= -lutil SRCS.bar= bar_src.c - The supported variables are BINDIR BINGRP BINMODE BINOWN - CFLAGS CXXFLAGS DEBUG_FLAGS DPADD DPSRCS LDADD - LDFLAGS LIBADD MAN MLINKS PROGNAME SRCS STRIP. + The supported variables are: + - BINDIR + - BINGRP + - BINMODE + - BINOWN + - CFLAGS + - CXXFLAGS + - DEBUG_FLAGS + - DPADD + - DPSRCS + - LDADD + - LDFLAGS + - LIBADD + - LINKS + - MAN + - MLINKS + - NO_WERROR + - PROGNAME + - SRCS + - STRIP + - WARNS PROGNAME The name that the above program will be installed as, if different from ${PROG}. From 13694b35e1e1e105655b4269939bfd7c8d46b469 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Thu, 14 Apr 2016 22:38:13 +0000 Subject: [PATCH 075/143] Add note about CAM I/O scheduler. --- UPDATING | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/UPDATING b/UPDATING index 2e4c37bb08d0..ac92b784f6e3 100644 --- a/UPDATING +++ b/UPDATING @@ -31,6 +31,13 @@ NOTE TO PEOPLE WHO THINK THAT FreeBSD 11.x IS SLOW: disable the most expensive debugging functionality run "ln -s 'abort:false,junk:false' /etc/malloc.conf".) +20160414: + The CAM I/O scheduler has been committed to the kernel. There should + be no user visible impact. This does enable NCQ Trim on ada + SSDs. While the list of known rogues that claim support for + this but actually corrupt data is believed to be complete, be + on the lookout for data corruption. + 20160330: The FAST_DEPEND build option has been removed and its functionality is now the one true way. The old mkdep(1) style of 'make depend' has From 2acdf79f5397a4bb7bfde3956a878a1956e0abfe Mon Sep 17 00:00:00 2001 From: "Andrey V. Elsukov" Date: Thu, 14 Apr 2016 22:51:23 +0000 Subject: [PATCH 076/143] Add External Actions KPI to ipfw(9). It allows implementing loadable kernel modules with new actions and without needing to modify kernel headers and ipfw(8). The module registers its action handler and keyword string, that will be used as action name. Using generic syntax user can add rules with this action. Also ipfw(8) can be easily modified to extend basic syntax for external actions, that become a part base system. Sample modules will coming soon. Obtained from: Yandex LLC Sponsored by: Yandex LLC --- sbin/ipfw/ipfw2.c | 153 ++++++++++- sbin/ipfw/ipfw2.h | 9 +- sbin/ipfw/tables.c | 39 +-- sys/conf/files | 1 + sys/modules/ipfw/Makefile | 2 +- sys/netinet/ip_fw.h | 8 +- sys/netpfil/ipfw/ip_fw2.c | 7 + sys/netpfil/ipfw/ip_fw_eaction.c | 369 +++++++++++++++++++++++++++ sys/netpfil/ipfw/ip_fw_private.h | 24 +- sys/netpfil/ipfw/ip_fw_sockopt.c | 125 ++++++++- sys/netpfil/ipfw/ip_fw_table_value.c | 9 +- 11 files changed, 685 insertions(+), 61 deletions(-) create mode 100644 sys/netpfil/ipfw/ip_fw_eaction.c diff --git a/sbin/ipfw/ipfw2.c b/sbin/ipfw/ipfw2.c index 74198b63584f..21b6229d42cd 100644 --- a/sbin/ipfw/ipfw2.c +++ b/sbin/ipfw/ipfw2.c @@ -234,6 +234,9 @@ static struct _s_x ether_types[] = { { NULL, 0 } }; +static struct _s_x rule_eactions[] = { + { NULL, 0 } /* terminator */ +}; static struct _s_x rule_actions[] = { { "accept", TOK_ACCEPT }, @@ -265,6 +268,7 @@ static struct _s_x rule_actions[] = { { "setdscp", TOK_SETDSCP }, { "call", TOK_CALL }, { "return", TOK_RETURN }, + { "eaction", TOK_EACTION }, { NULL, 0 } /* terminator */ }; @@ -381,6 +385,8 @@ static uint16_t pack_table(struct tidx *tstate, char *name); static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx); static void object_sort_ctlv(ipfw_obj_ctlv *ctlv); +static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, + uint16_t type); /* * Simple string buffer API. @@ -634,7 +640,7 @@ do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen) * with the string (-1 in case of failure). */ int -match_token(struct _s_x *table, char *string) +match_token(struct _s_x *table, const char *string) { struct _s_x *pt; uint i = strlen(string); @@ -646,7 +652,7 @@ match_token(struct _s_x *table, char *string) } /** - * match_token takes a table and a string, returns the value associated + * match_token_relaxed takes a table and a string, returns the value associated * with the string for the best match. * * Returns: @@ -655,7 +661,7 @@ match_token(struct _s_x *table, char *string) * -2 if more than one records match @string. */ int -match_token_relaxed(struct _s_x *table, char *string) +match_token_relaxed(struct _s_x *table, const char *string) { struct _s_x *pt, *m; int i, c; @@ -676,6 +682,18 @@ match_token_relaxed(struct _s_x *table, char *string) return (c > 0 ? -2: -1); } +int +get_token(struct _s_x *table, const char *string, const char *errbase) +{ + int tcmd; + + if ((tcmd = match_token_relaxed(table, string)) < 0) + errx(EX_USAGE, "%s %s %s", + (tcmd == 0) ? "invalid" : "ambiguous", errbase, string); + + return (tcmd); +} + /** * match_value takes a table and a value, returns the string associated * with the value (NULL in case of failure). @@ -1383,7 +1401,7 @@ show_static_rule(struct cmdline_opts *co, struct format_opts *fo, { static int twidth = 0; int l; - ipfw_insn *cmd, *tagptr = NULL; + ipfw_insn *cmd, *has_eaction = NULL, *tagptr = NULL; const char *comment = NULL; /* ptr to comment if we have one */ int proto = 0; /* default */ int flags = 0; /* prerequisites */ @@ -1567,6 +1585,52 @@ show_static_rule(struct cmdline_opts *co, struct format_opts *fo, bprint_uint_arg(bp, "setfib ", cmd->arg1 & 0x7FFF); break; + case O_EXTERNAL_ACTION: { + const char *ename; + + /* + * The external action can consists of two following + * each other opcodes - O_EXTERNAL_ACTION and + * O_EXTERNAL_INSTANCE. The first contains the ID of + * name of external action. The second contains the ID + * of name of external action instance. + * NOTE: in case when external action has no named + * instances support, the second opcode isn't needed. + */ + has_eaction = cmd; + ename = object_search_ctlv(fo->tstate, cmd->arg1, + IPFW_TLV_EACTION); + if (match_token(rule_eactions, ename) != -1) + bprintf(bp, "%s", ename); + else + bprintf(bp, "eaction %s", ename); + break; + } + + case O_EXTERNAL_INSTANCE: { + const char *ename; + + if (has_eaction == NULL) + break; + /* + * XXX: we need to teach ipfw(9) to rewrite opcodes + * in the user buffer on rule addition. When we add + * the rule, we specify zero TLV type for + * O_EXTERNAL_INSTANCE object. To show correct + * rule after `ipfw add` we need to search instance + * name with zero type. But when we do `ipfw show` + * we calculate TLV type using IPFW_TLV_EACTION_NAME() + * macro. + */ + ename = object_search_ctlv(fo->tstate, cmd->arg1, 0); + if (ename == NULL) + ename = object_search_ctlv(fo->tstate, + cmd->arg1, + IPFW_TLV_EACTION_NAME(has_eaction->arg1)); + bprintf(bp, " %s", ename); + break; + } + case O_SETDSCP: { const char *code; @@ -2730,6 +2794,42 @@ struct tidx { uint8_t set; }; +int +ipfw_check_object_name(const char *name) +{ + int c, i, l; + + /* + * Check that name is null-terminated and contains + * valid symbols only. Valid mask is: + * [a-zA-Z0-9\-_\.]{1,63} + */ + l = strlen(name); + if (l == 0 || l >= 64) + return (EINVAL); + for (i = 0; i < l; i++) { + c = name[i]; + if (isalpha(c) || isdigit(c) || c == '_' || + c == '-' || c == '.') + continue; + return (EINVAL); + } + return (0); +} + +static int +eaction_check_name(const char *name) +{ + + if (ipfw_check_object_name(name) != 0) + return (EINVAL); + /* Restrict some 'special' names */ + if (match_token(rule_actions, name) != -1 && + match_token(rule_action_params, name) != -1) + return (EINVAL); + return (0); +} + static uint16_t pack_object(struct tidx *tstate, char *name, int otype) { @@ -3833,7 +3933,46 @@ compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate) break; default: - errx(EX_DATAERR, "invalid action %s\n", av[-1]); + av--; + if (match_token(rule_eactions, *av) == -1) + errx(EX_DATAERR, "invalid action %s\n", *av); + /* + * External actions support. + * XXX: we support only syntax with instance name. + * For known external actions (from rule_eactions list) + * we can handle syntax directly. But with `eaction' + * keyword we can use only `eaction ' + * syntax. + */ + case TOK_EACTION: { + uint16_t idx; + + NEED1("Missing eaction name"); + if (eaction_check_name(*av) != 0) + errx(EX_DATAERR, "Invalid eaction name %s", *av); + idx = pack_object(tstate, *av, IPFW_TLV_EACTION); + if (idx == 0) + errx(EX_DATAERR, "pack_object failed"); + fill_cmd(action, O_EXTERNAL_ACTION, 0, idx); + av++; + NEED1("Missing eaction instance name"); + action = next_cmd(action, &ablen); + action->len = 1; + CHECK_ACTLEN; + if (eaction_check_name(*av) != 0) + errx(EX_DATAERR, "Invalid eaction instance name %s", + *av); + /* + * External action instance object has TLV type depended + * from the external action name object index. Since we + * currently don't know this index, use zero as TLV type. + */ + idx = pack_object(tstate, *av, 0); + if (idx == 0) + errx(EX_DATAERR, "pack_object failed"); + fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx); + av++; + } } action = next_cmd(action, &ablen); @@ -4758,7 +4897,7 @@ object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type) ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize, compare_object_kntlv); - if (ntlv != 0) + if (ntlv != NULL) return (ntlv->name); return (NULL); @@ -5019,7 +5158,7 @@ ipfw_list_objects(int ac, char *av[]) printf("There are no objects\n"); ntlv = (ipfw_obj_ntlv *)(olh + 1); for (i = 0; i < olh->count; i++) { - printf(" kidx: %4d\ttype: %2d\tname: %s\n", ntlv->idx, + printf(" kidx: %4d\ttype: %6d\tname: %s\n", ntlv->idx, ntlv->head.type, ntlv->name); ntlv++; } diff --git a/sbin/ipfw/ipfw2.h b/sbin/ipfw/ipfw2.h index 03c91e5672fd..d18803d510b9 100644 --- a/sbin/ipfw/ipfw2.h +++ b/sbin/ipfw/ipfw2.h @@ -83,6 +83,7 @@ enum tokens { TOK_ACCEPT, TOK_COUNT, + TOK_EACTION, TOK_PIPE, TOK_LINK, TOK_QUEUE, @@ -261,8 +262,9 @@ int _substrcmp2(const char *str1, const char* str2, const char* str3); int stringnum_cmp(const char *a, const char *b); /* utility functions */ -int match_token(struct _s_x *table, char *string); -int match_token_relaxed(struct _s_x *table, char *string); +int match_token(struct _s_x *table, const char *string); +int match_token_relaxed(struct _s_x *table, const char *string); +int get_token(struct _s_x *table, const char *string, const char *errbase); char const *match_value(struct _s_x *p, int value); size_t concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter); @@ -313,6 +315,7 @@ void ipfw_flush(int force); void ipfw_zero(int ac, char *av[], int optname); void ipfw_list(int ac, char *av[], int show_counters); void ipfw_internal_handler(int ac, char *av[]); +int ipfw_check_object_name(const char *name); #ifdef PF /* altq.c */ @@ -345,7 +348,7 @@ int fill_ext6hdr(struct _ipfw_insn *cmd, char *av); /* tables.c */ struct _ipfw_obj_ctlv; -int table_check_name(char *tablename); +int table_check_name(const char *tablename); void ipfw_list_ta(int ac, char *av[]); void ipfw_list_values(int ac, char *av[]); diff --git a/sbin/ipfw/tables.c b/sbin/ipfw/tables.c index 7eff340845f1..2264e3218980 100644 --- a/sbin/ipfw/tables.c +++ b/sbin/ipfw/tables.c @@ -53,8 +53,8 @@ static void table_lock(ipfw_obj_header *oh, int lock); static int table_swap(ipfw_obj_header *oh, char *second); static int table_get_info(ipfw_obj_header *oh, ipfw_xtable_info *i); static int table_show_info(ipfw_xtable_info *i, void *arg); -static void table_fill_ntlv(ipfw_obj_ntlv *ntlv, char *name, uint32_t set, - uint16_t uidx); +static void table_fill_ntlv(ipfw_obj_ntlv *ntlv, const char *name, + uint32_t set, uint16_t uidx); static int table_flush_one(ipfw_xtable_info *i, void *arg); static int table_show_one(ipfw_xtable_info *i, void *arg); @@ -130,18 +130,6 @@ lookup_host (char *host, struct in_addr *ipaddr) return(0); } -static int -get_token(struct _s_x *table, char *string, char *errbase) -{ - int tcmd; - - if ((tcmd = match_token_relaxed(table, string)) < 0) - errx(EX_USAGE, "%s %s %s", - (tcmd == 0) ? "invalid" : "ambiguous", errbase, string); - - return (tcmd); -} - /* * This one handles all table-related commands * ipfw table NAME create ... @@ -293,7 +281,8 @@ ipfw_table_handler(int ac, char *av[]) } static void -table_fill_ntlv(ipfw_obj_ntlv *ntlv, char *name, uint32_t set, uint16_t uidx) +table_fill_ntlv(ipfw_obj_ntlv *ntlv, const char *name, uint32_t set, + uint16_t uidx) { ntlv->head.type = IPFW_TLV_TBL_NAME; @@ -1994,30 +1983,14 @@ ipfw_list_values(int ac, char *av[]) } int -table_check_name(char *tablename) +table_check_name(const char *tablename) { - int c, i, l; - /* - * Check if tablename is null-terminated and contains - * valid symbols only. Valid mask is: - * [a-zA-Z0-9\-_\.]{1,63} - */ - l = strlen(tablename); - if (l == 0 || l >= 64) + if (ipfw_check_object_name(tablename) != 0) return (EINVAL); - for (i = 0; i < l; i++) { - c = tablename[i]; - if (isalpha(c) || isdigit(c) || c == '_' || - c == '-' || c == '.') - continue; - return (EINVAL); - } - /* Restrict some 'special' names */ if (strcmp(tablename, "all") == 0) return (EINVAL); - return (0); } diff --git a/sys/conf/files b/sys/conf/files index 8831f5c2eb6c..77169fa6316e 100644 --- a/sys/conf/files +++ b/sys/conf/files @@ -3749,6 +3749,7 @@ netpfil/ipfw/ip_dn_io.c optional inet dummynet netpfil/ipfw/ip_dn_glue.c optional inet dummynet netpfil/ipfw/ip_fw2.c optional inet ipfirewall netpfil/ipfw/ip_fw_dynamic.c optional inet ipfirewall +netpfil/ipfw/ip_fw_eaction.c optional inet ipfirewall netpfil/ipfw/ip_fw_log.c optional inet ipfirewall netpfil/ipfw/ip_fw_pfil.c optional inet ipfirewall netpfil/ipfw/ip_fw_sockopt.c optional inet ipfirewall diff --git a/sys/modules/ipfw/Makefile b/sys/modules/ipfw/Makefile index a0045f3ca607..f25762d291a3 100644 --- a/sys/modules/ipfw/Makefile +++ b/sys/modules/ipfw/Makefile @@ -4,7 +4,7 @@ KMOD= ipfw SRCS= ip_fw2.c ip_fw_pfil.c -SRCS+= ip_fw_dynamic.c ip_fw_log.c +SRCS+= ip_fw_dynamic.c ip_fw_log.c ip_fw_eaction.c SRCS+= ip_fw_sockopt.c ip_fw_table.c ip_fw_table_algo.c ip_fw_iface.c SRCS+= ip_fw_table_value.c SRCS+= opt_inet.h opt_inet6.h opt_ipdivert.h opt_ipfw.h opt_ipsec.h diff --git a/sys/netinet/ip_fw.h b/sys/netinet/ip_fw.h index e52ff1a54cb3..7250527476e7 100644 --- a/sys/netinet/ip_fw.h +++ b/sys/netinet/ip_fw.h @@ -256,10 +256,12 @@ enum ipfw_opcodes { /* arguments (4 byte each) */ O_SETDSCP, /* arg1=DSCP value */ O_IP_FLOW_LOOKUP, /* arg1=table number, u32=value */ + O_EXTERNAL_ACTION, /* arg1=id of external action handler */ + O_EXTERNAL_INSTANCE, /* arg1=id of eaction handler instance */ + O_LAST_OPCODE /* not an opcode! */ }; - /* * The extension header are filtered only for presence using a bit * vector with a flag for each header. @@ -780,6 +782,10 @@ typedef struct _ipfw_obj_tlv { #define IPFW_TLV_RULE_ENT 7 #define IPFW_TLV_TBLENT_LIST 8 #define IPFW_TLV_RANGE 9 +#define IPFW_TLV_EACTION 10 + +#define IPFW_TLV_EACTION_BASE 1000 +#define IPFW_TLV_EACTION_NAME(arg) (IPFW_TLV_EACTION_BASE + (arg)) /* Object name TLV */ typedef struct _ipfw_obj_ntlv { diff --git a/sys/netpfil/ipfw/ip_fw2.c b/sys/netpfil/ipfw/ip_fw2.c index 2d0d2f40bb70..b0a74744c9d6 100644 --- a/sys/netpfil/ipfw/ip_fw2.c +++ b/sys/netpfil/ipfw/ip_fw2.c @@ -2542,6 +2542,11 @@ do { \ done = 1; /* exit outer loop */ break; } + case O_EXTERNAL_ACTION: + l = 0; /* in any case exit inner loop */ + retval = ipfw_run_eaction(chain, args, + cmd, &done); + break; default: panic("-- unknown opcode %d\n", cmd->opcode); @@ -2766,6 +2771,7 @@ vnet_ipfw_init(const void *unused) IPFW_LOCK_INIT(chain); ipfw_dyn_init(chain); + ipfw_eaction_init(chain, first); #ifdef LINEAR_SKIPTO ipfw_init_skipto_cache(chain); #endif @@ -2830,6 +2836,7 @@ vnet_ipfw_uninit(const void *unused) IPFW_WUNLOCK(chain); IPFW_UH_WUNLOCK(chain); ipfw_destroy_tables(chain, last); + ipfw_eaction_uninit(chain, last); if (reap != NULL) ipfw_reap_rules(reap); vnet_ipfw_iface_destroy(chain); diff --git a/sys/netpfil/ipfw/ip_fw_eaction.c b/sys/netpfil/ipfw/ip_fw_eaction.c new file mode 100644 index 000000000000..144bf49db381 --- /dev/null +++ b/sys/netpfil/ipfw/ip_fw_eaction.c @@ -0,0 +1,369 @@ +/*- + * Copyright (c) 2016 Yandex LLC + * Copyright (c) 2016 Andrey V. Elsukov + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD$"); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include /* ip_fw.h requires IFNAMSIZ */ +#include +#include /* struct ipfw_rule_ref */ +#include + +#include + +#include "opt_ipfw.h" + +/* + * External actions support for ipfw. + * + * This code provides KPI for implementing loadable modules, that + * can provide handlers for external action opcodes in the ipfw's + * rules. + * Module should implement opcode handler with type ipfw_eaction_t. + * This handler will be called by ipfw_chk() function when + * O_EXTERNAL_ACTION opcode will be matched. The handler must return + * value used as return value in ipfw_chk(), i.e. IP_FW_PASS, + * IP_FW_DENY (see ip_fw_private.h). + * Also the last argument must be set by handler. If it is zero, + * the search continues to the next rule. If it has non zero value, + * the search terminates. + * + * The module that implements external action should register its + * handler and name with ipfw_add_eaction() function. + * This function will return eaction_id, that can be used by module. + * + * It is possible to pass some additional information to external + * action handler via the O_EXTERNAL_INSTANCE opcode. This opcode + * will be next after the O_EXTERNAL_ACTION opcode. cmd->arg1 will + * contain index of named object related to instance of external action. + * + * In case when eaction module uses named instances, it should register + * opcode rewriting routines for O_EXTERNAL_INSTANCE opcode. The + * classifier callback can look back into O_EXTERNAL_ACTION opcode (it + * must be in the (ipfw_insn *)(cmd - 1)). By arg1 from O_EXTERNAL_ACTION + * it can deteremine eaction_id and compare it with its own. + * The macro IPFW_TLV_EACTION_NAME(eaction_id) can be used to deteremine + * the type of named_object related to external action instance. + * + * On module unload handler should be deregistered with ipfw_del_eaction() + * function using known eaction_id. + */ + +struct eaction_obj { + struct named_object no; + ipfw_eaction_t *handler; + char name[64]; +}; + +#define EACTION_OBJ(ch, cmd) \ + ((struct eaction_obj *)SRV_OBJECT((ch), (cmd)->arg1)) + +#if 0 +#define EACTION_DEBUG(fmt, ...) do { \ + printf("%s: " fmt "\n", __func__, ## __VA_ARGS__); \ +} while (0) +#else +#define EACTION_DEBUG(fmt, ...) +#endif + +const char *default_eaction_typename = "drop"; +static int +default_eaction(struct ip_fw_chain *ch, struct ip_fw_args *args, + ipfw_insn *cmd, int *done) +{ + + *done = 1; /* terminate the search */ + return (IP_FW_DENY); +} + +/* + * Opcode rewriting callbacks. + */ +static int +eaction_classify(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype) +{ + + EACTION_DEBUG("opcode %d, arg1 %d", cmd->opcode, cmd->arg1); + *puidx = cmd->arg1; + *ptype = 0; + return (0); +} + +static void +eaction_update(ipfw_insn *cmd, uint16_t idx) +{ + + cmd->arg1 = idx; + EACTION_DEBUG("opcode %d, arg1 -> %d", cmd->opcode, cmd->arg1); +} + +static int +eaction_findbyname(struct ip_fw_chain *ch, struct tid_info *ti, + struct named_object **pno) +{ + + EACTION_DEBUG("uidx %u, type %u", ti->uidx, ti->type); + return (ipfw_objhash_find_type(CHAIN_TO_SRV(ch), ti, + IPFW_TLV_EACTION, pno)); +} + +static struct named_object * +eaction_findbykidx(struct ip_fw_chain *ch, uint16_t idx) +{ + + EACTION_DEBUG("kidx %u", idx); + return (ipfw_objhash_lookup_kidx(CHAIN_TO_SRV(ch), idx)); +} + +static int +eaction_create_compat(struct ip_fw_chain *ch, struct tid_info *ti, + uint16_t *pkidx) +{ + + return (EOPNOTSUPP); +} + +static struct opcode_obj_rewrite eaction_opcodes[] = { + { + O_EXTERNAL_ACTION, IPFW_TLV_EACTION, + eaction_classify, eaction_update, + eaction_findbyname, eaction_findbykidx, + eaction_create_compat + }, +}; + +static int +create_eaction_obj(struct ip_fw_chain *ch, ipfw_eaction_t handler, + const char *name, uint16_t *eaction_id) +{ + struct namedobj_instance *ni; + struct eaction_obj *obj; + + IPFW_UH_UNLOCK_ASSERT(ch); + + ni = CHAIN_TO_SRV(ch); + obj = malloc(sizeof(*obj), M_IPFW, M_WAITOK | M_ZERO); + obj->no.name = obj->name; + obj->no.etlv = IPFW_TLV_EACTION; + obj->handler = handler; + strlcpy(obj->name, name, sizeof(obj->name)); + + IPFW_UH_WLOCK(ch); + if (ipfw_objhash_lookup_name_type(ni, 0, IPFW_TLV_EACTION, + name) != NULL) { + /* + * Object is already created. + * We don't allow eactions with the same name. + */ + IPFW_UH_WUNLOCK(ch); + free(obj, M_IPFW); + EACTION_DEBUG("External action with typename " + "'%s' already exists", name); + return (EEXIST); + } + if (ipfw_objhash_alloc_idx(ni, &obj->no.kidx) != 0) { + IPFW_UH_WUNLOCK(ch); + free(obj, M_IPFW); + EACTION_DEBUG("alloc_idx failed"); + return (ENOSPC); + } + ipfw_objhash_add(ni, &obj->no); + IPFW_WLOCK(ch); + SRV_OBJECT(ch, obj->no.kidx) = obj; + IPFW_WUNLOCK(ch); + obj->no.refcnt++; + IPFW_UH_WUNLOCK(ch); + + if (eaction_id != NULL) + *eaction_id = obj->no.kidx; + return (0); +} + +static void +destroy_eaction_obj(struct ip_fw_chain *ch, struct named_object *no) +{ + struct namedobj_instance *ni; + struct eaction_obj *obj; + + IPFW_UH_WLOCK_ASSERT(ch); + + ni = CHAIN_TO_SRV(ch); + IPFW_WLOCK(ch); + obj = SRV_OBJECT(ch, no->kidx); + SRV_OBJECT(ch, no->kidx) = NULL; + IPFW_WUNLOCK(ch); + ipfw_objhash_del(ni, no); + ipfw_objhash_free_idx(ni, no->kidx); + free(obj, M_IPFW); +} + +/* + * Resets all eaction opcodes to default handlers. + */ +static void +reset_eaction_obj(struct ip_fw_chain *ch, uint16_t eaction_id) +{ + struct named_object *no; + struct ip_fw *rule; + ipfw_insn *cmd; + int i; + + IPFW_UH_WLOCK_ASSERT(ch); + + no = ipfw_objhash_lookup_name_type(CHAIN_TO_SRV(ch), 0, + IPFW_TLV_EACTION, default_eaction_typename); + if (no == NULL) + panic("Default external action handler is not found"); + if (eaction_id == no->kidx) + panic("Wrong eaction_id"); + EACTION_DEBUG("replace id %u with %u", eaction_id, no->kidx); + IPFW_WLOCK(ch); + for (i = 0; i < ch->n_rules; i++) { + rule = ch->map[i]; + cmd = ACTION_PTR(rule); + if (cmd->opcode != O_EXTERNAL_ACTION) + continue; + if (cmd->arg1 != eaction_id) + continue; + cmd->arg1 = no->kidx; /* Set to default id */ + /* + * XXX: we only bump refcount on default_eaction. + * Refcount on the original object will be just + * ignored on destroy. But on default_eaction it + * will be decremented on rule deletion. + */ + no->refcnt++; + /* + * Since named_object related to this instance will be + * also destroyed, truncate the chain of opcodes to + * remove O_EXTERNAL_INSTANCE opcode. + */ + if (rule->act_ofs < rule->cmd_len - 1) { + EACTION_DEBUG("truncate rule %d", rule->rulenum); + rule->cmd_len--; + } + } + IPFW_WUNLOCK(ch); +} + +/* + * Initialize external actions framework. + * Create object with default eaction handler "drop". + */ +int +ipfw_eaction_init(struct ip_fw_chain *ch, int first) +{ + int error; + + error = create_eaction_obj(ch, default_eaction, + default_eaction_typename, NULL); + if (error != 0) + return (error); + IPFW_ADD_OBJ_REWRITER(first, eaction_opcodes); + EACTION_DEBUG("External actions support initialized"); + return (0); +} + +void +ipfw_eaction_uninit(struct ip_fw_chain *ch, int last) +{ + struct namedobj_instance *ni; + struct named_object *no; + + ni = CHAIN_TO_SRV(ch); + + IPFW_UH_WLOCK(ch); + no = ipfw_objhash_lookup_name_type(ni, 0, IPFW_TLV_EACTION, + default_eaction_typename); + if (no != NULL) + destroy_eaction_obj(ch, no); + IPFW_UH_WUNLOCK(ch); + IPFW_DEL_OBJ_REWRITER(last, eaction_opcodes); + EACTION_DEBUG("External actions support uninitialized"); +} + +/* + * Registers external action handler to the global array. + * On success it returns eaction id, otherwise - zero. + */ +uint16_t +ipfw_add_eaction(struct ip_fw_chain *ch, ipfw_eaction_t handler, + const char *name) +{ + uint16_t eaction_id; + + eaction_id = 0; + if (ipfw_check_object_name_generic(name) == 0) { + create_eaction_obj(ch, handler, name, &eaction_id); + EACTION_DEBUG("Registered external action '%s' with id %u", + name, eaction_id); + } + return (eaction_id); +} + +/* + * Deregisters external action handler with id eaction_id. + */ +int +ipfw_del_eaction(struct ip_fw_chain *ch, uint16_t eaction_id) +{ + struct named_object *no; + + IPFW_UH_WLOCK(ch); + no = ipfw_objhash_lookup_kidx(CHAIN_TO_SRV(ch), eaction_id); + if (no == NULL || no->etlv != IPFW_TLV_EACTION) { + IPFW_UH_WUNLOCK(ch); + return (EINVAL); + } + if (no->refcnt > 1) + reset_eaction_obj(ch, eaction_id); + EACTION_DEBUG("External action '%s' with id %u unregistered", + no->name, eaction_id); + destroy_eaction_obj(ch, no); + IPFW_UH_WUNLOCK(ch); + return (0); +} + +int +ipfw_run_eaction(struct ip_fw_chain *ch, struct ip_fw_args *args, + ipfw_insn *cmd, int *done) +{ + + return (EACTION_OBJ(ch, cmd)->handler(ch, args, cmd, done)); +} diff --git a/sys/netpfil/ipfw/ip_fw_private.h b/sys/netpfil/ipfw/ip_fw_private.h index 97c1a78eddf8..62e1a9a5df16 100644 --- a/sys/netpfil/ipfw/ip_fw_private.h +++ b/sys/netpfil/ipfw/ip_fw_private.h @@ -516,9 +516,10 @@ struct ip_fw_bcounter0 { #define IPFW_TABLES_MAX 65536 #define IPFW_TABLES_DEFAULT 128 #define IPFW_OBJECTS_MAX 65536 -#define IPFW_OBJECTS_DEFAULT 128 +#define IPFW_OBJECTS_DEFAULT 1024 #define CHAIN_TO_SRV(ch) ((ch)->srvmap) +#define SRV_OBJECT(ch, idx) ((ch)->srvstate[(idx)]) struct tid_info { uint32_t set; /* table set */ @@ -650,9 +651,10 @@ caddr_t ipfw_get_sopt_header(struct sockopt_data *sd, size_t needed); struct namedobj_instance; typedef void (objhash_cb_t)(struct namedobj_instance *ni, struct named_object *, void *arg); -typedef uint32_t (objhash_hash_f)(struct namedobj_instance *ni, void *key, +typedef uint32_t (objhash_hash_f)(struct namedobj_instance *ni, const void *key, + uint32_t kopt); +typedef int (objhash_cmp_f)(struct named_object *no, const void *key, uint32_t kopt); -typedef int (objhash_cmp_f)(struct named_object *no, void *key, uint32_t kopt); struct namedobj_instance *ipfw_objhash_create(uint32_t items); void ipfw_objhash_destroy(struct namedobj_instance *); void ipfw_objhash_bitmap_alloc(uint32_t items, void **idx, int *pblocks); @@ -665,7 +667,7 @@ void ipfw_objhash_set_hashf(struct namedobj_instance *ni, objhash_hash_f *f); struct named_object *ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name); struct named_object *ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, - uint32_t set, uint32_t type, char *name); + uint32_t set, uint32_t type, const char *name); struct named_object *ipfw_objhash_lookup_kidx(struct namedobj_instance *ni, uint16_t idx); int ipfw_objhash_same_name(struct namedobj_instance *ni, struct named_object *a, @@ -679,6 +681,8 @@ int ipfw_objhash_free_idx(struct namedobj_instance *ni, uint16_t idx); int ipfw_objhash_alloc_idx(void *n, uint16_t *pidx); void ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f, objhash_cmp_f *cmp_f); +int ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti, + uint32_t etlv, struct named_object **pno); void ipfw_export_obj_ntlv(struct named_object *no, ipfw_obj_ntlv *ntlv); void ipfw_init_obj_rewriter(void); void ipfw_destroy_obj_rewriter(void); @@ -693,6 +697,18 @@ void ipfw_init_srv(struct ip_fw_chain *ch); void ipfw_destroy_srv(struct ip_fw_chain *ch); int ipfw_check_object_name_generic(const char *name); +/* In ip_fw_eaction.c */ +typedef int (ipfw_eaction_t)(struct ip_fw_chain *ch, struct ip_fw_args *args, + ipfw_insn *cmd, int *done); +int ipfw_eaction_init(struct ip_fw_chain *ch, int first); +void ipfw_eaction_uninit(struct ip_fw_chain *ch, int last); + +uint16_t ipfw_add_eaction(struct ip_fw_chain *ch, ipfw_eaction_t handler, + const char *name); +int ipfw_del_eaction(struct ip_fw_chain *ch, uint16_t eaction_id); +int ipfw_run_eaction(struct ip_fw_chain *ch, struct ip_fw_args *args, + ipfw_insn *cmd, int *done); + /* In ip_fw_table.c */ struct table_info; diff --git a/sys/netpfil/ipfw/ip_fw_sockopt.c b/sys/netpfil/ipfw/ip_fw_sockopt.c index 814445162939..00d1a0aaf1af 100644 --- a/sys/netpfil/ipfw/ip_fw_sockopt.c +++ b/sys/netpfil/ipfw/ip_fw_sockopt.c @@ -100,10 +100,11 @@ struct namedobj_instance { }; #define BLOCK_ITEMS (8 * sizeof(u_long)) /* Number of items for ffsl() */ -static uint32_t objhash_hash_name(struct namedobj_instance *ni, void *key, - uint32_t kopt); +static uint32_t objhash_hash_name(struct namedobj_instance *ni, + const void *key, uint32_t kopt); static uint32_t objhash_hash_idx(struct namedobj_instance *ni, uint32_t val); -static int objhash_cmp_name(struct named_object *no, void *name, uint32_t set); +static int objhash_cmp_name(struct named_object *no, const void *name, + uint32_t set); MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's"); @@ -1492,6 +1493,35 @@ check_ipfw_rule_body(ipfw_insn *cmd, int cmd_len, struct rule_check_info *ci) goto bad_size; break; + case O_EXTERNAL_ACTION: + if (cmd->arg1 == 0 || + cmdlen != F_INSN_SIZE(ipfw_insn)) { + printf("ipfw: invalid external " + "action opcode\n"); + return (EINVAL); + } + ci->object_opcodes++; + /* Do we have O_EXTERNAL_INSTANCE opcode? */ + if (l != cmdlen) { + l -= cmdlen; + cmd += cmdlen; + cmdlen = F_LEN(cmd); + if (cmd->opcode != O_EXTERNAL_INSTANCE) { + printf("ipfw: invalid opcode " + "next to external action %u\n", + cmd->opcode); + return (EINVAL); + } + if (cmd->arg1 == 0 || + cmdlen != F_INSN_SIZE(ipfw_insn)) { + printf("ipfw: invalid external " + "action instance opcode\n"); + return (EINVAL); + } + ci->object_opcodes++; + } + goto check_action; + case O_FIB: if (cmdlen != F_INSN_SIZE(ipfw_insn)) goto bad_size; @@ -4008,17 +4038,17 @@ ipfw_objhash_set_funcs(struct namedobj_instance *ni, objhash_hash_f *hash_f, } static uint32_t -objhash_hash_name(struct namedobj_instance *ni, void *name, uint32_t set) +objhash_hash_name(struct namedobj_instance *ni, const void *name, uint32_t set) { - return (fnv_32_str((char *)name, FNV1_32_INIT)); + return (fnv_32_str((const char *)name, FNV1_32_INIT)); } static int -objhash_cmp_name(struct named_object *no, void *name, uint32_t set) +objhash_cmp_name(struct named_object *no, const void *name, uint32_t set) { - if ((strcmp(no->name, (char *)name) == 0) && (no->set == set)) + if ((strcmp(no->name, (const char *)name) == 0) && (no->set == set)) return (0); return (1); @@ -4050,12 +4080,91 @@ ipfw_objhash_lookup_name(struct namedobj_instance *ni, uint32_t set, char *name) return (NULL); } +/* + * Find named object by @uid. + * Check @tlvs for valid data inside. + * + * Returns pointer to found TLV or NULL. + */ +static ipfw_obj_ntlv * +find_name_tlv_type(void *tlvs, int len, uint16_t uidx, uint32_t etlv) +{ + ipfw_obj_ntlv *ntlv; + uintptr_t pa, pe; + int l; + + pa = (uintptr_t)tlvs; + pe = pa + len; + l = 0; + for (; pa < pe; pa += l) { + ntlv = (ipfw_obj_ntlv *)pa; + l = ntlv->head.length; + + if (l != sizeof(*ntlv)) + return (NULL); + + if (ntlv->idx != uidx) + continue; + /* + * When userland has specified zero TLV type, do + * not compare it with eltv. In some cases userland + * doesn't know what type should it have. Use only + * uidx and name for search named_object. + */ + if (ntlv->head.type != 0 && + ntlv->head.type != (uint16_t)etlv) + continue; + + if (ipfw_check_object_name_generic(ntlv->name) != 0) + return (NULL); + + return (ntlv); + } + + return (NULL); +} + +/* + * Finds object config based on either legacy index + * or name in ntlv. + * Note @ti structure contains unchecked data from userland. + * + * Returns 0 in success and fills in @pno with found config + */ +int +ipfw_objhash_find_type(struct namedobj_instance *ni, struct tid_info *ti, + uint32_t etlv, struct named_object **pno) +{ + char *name; + ipfw_obj_ntlv *ntlv; + uint32_t set; + + if (ti->tlvs == NULL) + return (EINVAL); + + ntlv = find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx, etlv); + if (ntlv == NULL) + return (EINVAL); + name = ntlv->name; + + /* + * Use set provided by @ti instead of @ntlv one. + * This is needed due to different sets behavior + * controlled by V_fw_tables_sets. + */ + set = ti->set; + *pno = ipfw_objhash_lookup_name(ni, set, name); + if (*pno == NULL) + return (ESRCH); + return (0); +} + /* * Find named object by name, considering also its TLV type. */ struct named_object * ipfw_objhash_lookup_name_type(struct namedobj_instance *ni, uint32_t set, - uint32_t type, char *name) + uint32_t type, const char *name) { struct named_object *no; uint32_t hash; diff --git a/sys/netpfil/ipfw/ip_fw_table_value.c b/sys/netpfil/ipfw/ip_fw_table_value.c index a196b030ebf0..7e2f5cb8f746 100644 --- a/sys/netpfil/ipfw/ip_fw_table_value.c +++ b/sys/netpfil/ipfw/ip_fw_table_value.c @@ -58,9 +58,10 @@ __FBSDID("$FreeBSD$"); #include #include -static uint32_t hash_table_value(struct namedobj_instance *ni, void *key, +static uint32_t hash_table_value(struct namedobj_instance *ni, const void *key, + uint32_t kopt); +static int cmp_table_value(struct named_object *no, const void *key, uint32_t kopt); -static int cmp_table_value(struct named_object *no, void *key, uint32_t kopt); static int list_table_values(struct ip_fw_chain *ch, ip_fw3_opheader *op3, struct sockopt_data *sd); @@ -87,14 +88,14 @@ struct vdump_args { static uint32_t -hash_table_value(struct namedobj_instance *ni, void *key, uint32_t kopt) +hash_table_value(struct namedobj_instance *ni, const void *key, uint32_t kopt) { return (hash32_buf(key, 56, 0)); } static int -cmp_table_value(struct named_object *no, void *key, uint32_t kopt) +cmp_table_value(struct named_object *no, const void *key, uint32_t kopt) { return (memcmp(((struct table_val_link *)no)->pval, key, 56)); From c29088b5c74d5b01982ffd217ea6a6ef14d6a93b Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Thu, 14 Apr 2016 23:14:41 +0000 Subject: [PATCH 077/143] Add more debugging statements in vdev_geom.c Log a debugging message whenever geom functions fail in vdev_geom_attach. Printing these messages is controlled by vfs.zfs.debug MFC after: 4 weeks Sponsored by: Spectra Logic Corp --- .../opensolaris/uts/common/fs/zfs/vdev_geom.c | 27 +++++++++++++++---- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c index edea99f97169..bc63fe94c6a2 100644 --- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c +++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c @@ -163,6 +163,7 @@ vdev_geom_attach(struct g_provider *pp, vdev_t *vd) { struct g_geom *gp; struct g_consumer *cp; + int error; g_topology_assert(); @@ -180,11 +181,17 @@ vdev_geom_attach(struct g_provider *pp, vdev_t *vd) gp->orphan = vdev_geom_orphan; gp->attrchanged = vdev_geom_attrchanged; cp = g_new_consumer(gp); - if (g_attach(cp, pp) != 0) { + error = g_attach(cp, pp); + if (error != 0) { + ZFS_LOG(1, "%s(%d): g_attach failed: %d\n", __func__, + __LINE__, error); g_wither_geom(gp, ENXIO); return (NULL); } - if (g_access(cp, 1, 0, 1) != 0) { + error = g_access(cp, 1, 0, 1); + if (error != 0) { + ZFS_LOG(1, "%s(%d): g_access failed: %d\n", __func__, + __LINE__, error); g_wither_geom(gp, ENXIO); return (NULL); } @@ -199,19 +206,29 @@ vdev_geom_attach(struct g_provider *pp, vdev_t *vd) } if (cp == NULL) { cp = g_new_consumer(gp); - if (g_attach(cp, pp) != 0) { + error = g_attach(cp, pp); + if (error != 0) { + ZFS_LOG(1, "%s(%d): g_attach failed: %d\n", + __func__, __LINE__, error); g_destroy_consumer(cp); return (NULL); } - if (g_access(cp, 1, 0, 1) != 0) { + error = g_access(cp, 1, 0, 1); + if (error != 0) { + ZFS_LOG(1, "%s(%d): g_access failed: %d\n", + __func__, __LINE__, error); g_detach(cp); g_destroy_consumer(cp); return (NULL); } ZFS_LOG(1, "Created consumer for %s.", pp->name); } else { - if (g_access(cp, 1, 0, 1) != 0) + error = g_access(cp, 1, 0, 1); + if (error != 0) { + ZFS_LOG(1, "%s(%d): g_access failed: %d\n", + __func__, __LINE__, error); return (NULL); + } ZFS_LOG(1, "Used existing consumer for %s.", pp->name); } } From 1e6a0e5d79a858eb709313ba65647c606400d5d3 Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Fri, 15 Apr 2016 00:47:30 +0000 Subject: [PATCH 078/143] Initialize pointer with NULL instead of 0. Submitted by: pfg --- lib/libypclnt/ypclnt_passwd.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/libypclnt/ypclnt_passwd.c b/lib/libypclnt/ypclnt_passwd.c index c7ee7eafb108..86844eb48e99 100644 --- a/lib/libypclnt/ypclnt_passwd.c +++ b/lib/libypclnt/ypclnt_passwd.c @@ -65,7 +65,7 @@ int ypclnt_havepasswdd(ypclnt_t *ypclnt) { struct netconfig *nc = NULL; - void *localhandle = 0; + void *localhandle = NULL; CLIENT *clnt = NULL; int ret; @@ -139,7 +139,7 @@ yppasswd_local(ypclnt_t *ypclnt, const struct passwd *pwd) struct master_yppasswd yppwd; struct rpc_err rpcerr; struct netconfig *nc = NULL; - void *localhandle = 0; + void *localhandle = NULL; CLIENT *clnt = NULL; int ret, *result; From 69f23055872370098a1d7a9a7bd8804146698d66 Mon Sep 17 00:00:00 2001 From: Justin Hibbits Date: Fri, 15 Apr 2016 01:45:05 +0000 Subject: [PATCH 079/143] Add fman and dpaa fixups for powerpc fdt Obtained from: Semihalf --- sys/dev/fdt/fdt_powerpc.c | 65 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 3 deletions(-) diff --git a/sys/dev/fdt/fdt_powerpc.c b/sys/dev/fdt/fdt_powerpc.c index f408d0a30698..80cfa4b3a93a 100644 --- a/sys/dev/fdt/fdt_powerpc.c +++ b/sys/dev/fdt/fdt_powerpc.c @@ -46,7 +46,7 @@ __FBSDID("$FreeBSD$"); #include "fdt_common.h" static void -fdt_fixup_busfreq(phandle_t root) +fdt_fixup_busfreq(phandle_t root, uint32_t div) { phandle_t sb, cpus, child; pcell_t freq; @@ -72,12 +72,71 @@ fdt_fixup_busfreq(phandle_t root) sizeof(freq)) <= 0) return; + if (div == 0) + return; + + freq /= div; + OF_setprop(sb, "bus-frequency", (void *)&freq, sizeof(freq)); } +static void +fdt_fixup_busfreq_mpc85xx(phandle_t root) +{ + + fdt_fixup_busfreq(root, 1); +} + +static void +fdt_fixup_busfreq_dpaa(phandle_t root) +{ + + fdt_fixup_busfreq(root, 2); +} + +static void +fdt_fixup_fman(phandle_t root) +{ + phandle_t node; + pcell_t freq; + + if ((node = fdt_find_compatible(root, "simple-bus", 1)) == 0) + return; + + if (OF_getprop(node, "bus-frequency", (void *)&freq, + sizeof(freq)) <= 0) + return; + + /* + * Set clock-frequency for FMan nodes (only on QorIQ DPAA targets). + * That frequency is equal to /soc node bus-frequency. + */ + for (node = OF_child(node); node != 0; node = OF_peer(node)) { + if (fdt_is_compatible(node, "fsl,fman") == 0) + continue; + + if (OF_setprop(node, "clock-frequency", (void *)&freq, + sizeof(freq)) == -1) { + /* + * XXX Shall we take some actions if no clock-frequency + * property was found? + */ + } + } +} + struct fdt_fixup_entry fdt_fixup_table[] = { - { "fsl,MPC8572DS", &fdt_fixup_busfreq }, - { "MPC8555CDS", &fdt_fixup_busfreq }, + { "fsl,MPC8572DS", &fdt_fixup_busfreq_mpc85xx }, + { "MPC8555CDS", &fdt_fixup_busfreq_mpc85xx }, + { "fsl,P2020", &fdt_fixup_busfreq_mpc85xx }, + { "fsl,P2041RDB", &fdt_fixup_busfreq_dpaa }, + { "fsl,P2041RDB", &fdt_fixup_fman }, + { "fsl,P3041DS", &fdt_fixup_busfreq_dpaa }, + { "fsl,P3041DS", &fdt_fixup_fman }, + { "fsl,P5020DS", &fdt_fixup_busfreq_dpaa }, + { "fsl,P5020DS", &fdt_fixup_fman }, + { "varisys,CYRUS", &fdt_fixup_busfreq_dpaa }, + { "varisys,CYRUS", &fdt_fixup_fman }, { NULL, NULL } }; From 960536b69fcc255b15815acbae7cdc1b9cac3013 Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Fri, 15 Apr 2016 02:14:11 +0000 Subject: [PATCH 080/143] Use NULL instead of 0 for pointers and memory allocation. malloc and realloc will return NULL pointer if it can't alloc memory. MFC after: 4 weeks --- usr.sbin/fdformat/fdformat.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/usr.sbin/fdformat/fdformat.c b/usr.sbin/fdformat/fdformat.c index 341a161d1831..b7bab867951d 100644 --- a/usr.sbin/fdformat/fdformat.c +++ b/usr.sbin/fdformat/fdformat.c @@ -95,7 +95,7 @@ verify_track(int fd, int track, int tracksize) if (bufsz < tracksize) buf = realloc(buf, bufsz = tracksize); - if (buf == 0) + if (buf == NULL) errx(EX_UNAVAILABLE, "out of memory"); if (lseek (fd, (long) track * tracksize, 0) < 0) rv = -1; @@ -205,7 +205,7 @@ main(int argc, char **argv) if (stat(argv[optind], &sb) == -1 && errno == ENOENT) { /* try prepending _PATH_DEV */ device = malloc(strlen(argv[optind]) + sizeof(_PATH_DEV) + 1); - if (device == 0) + if (device == NULL) errx(EX_UNAVAILABLE, "out of memory"); strcpy(device, _PATH_DEV); strcat(device, argv[optind]); @@ -252,7 +252,7 @@ main(int argc, char **argv) if (format) { getname(type, &name, &descr); fdtp = get_fmt(format, type); - if (fdtp == 0) + if (fdtp == NULL) errx(EX_USAGE, "unknown format %d KB for drive type %s", format, name); From 0c29fe6db8a9154dd9f1dec774ed32d82e08cd8b Mon Sep 17 00:00:00 2001 From: Sepherosa Ziehau Date: Fri, 15 Apr 2016 02:20:18 +0000 Subject: [PATCH 081/143] hyperv: Deprecate HYPERV option by moving Hyper-V IDT vector into vmbus Submitted by: Jun Su Reviewed by: jhb, kib, sephe Sponsored by: Microsoft OSTC Differential Revision: https://reviews.freebsd.org/D5910 --- sys/amd64/amd64/apic_vector.S | 16 ------- sys/amd64/conf/GENERIC | 2 - sys/amd64/conf/NOTES | 1 - sys/conf/files.amd64 | 1 + sys/conf/files.i386 | 1 + sys/conf/options.amd64 | 2 - sys/conf/options.i386 | 2 - sys/dev/hyperv/vmbus/amd64/hv_vector.S | 46 +++++++++++++++++++ sys/dev/hyperv/vmbus/hv_vmbus_drv_freebsd.c | 6 --- sys/dev/hyperv/vmbus/i386/hv_vector.S | 49 +++++++++++++++++++++ sys/i386/conf/GENERIC | 2 - sys/i386/i386/apic_vector.s | 19 -------- sys/modules/hyperv/vmbus/Makefile | 15 +++++-- 13 files changed, 109 insertions(+), 53 deletions(-) create mode 100644 sys/dev/hyperv/vmbus/amd64/hv_vector.S create mode 100644 sys/dev/hyperv/vmbus/i386/hv_vector.S diff --git a/sys/amd64/amd64/apic_vector.S b/sys/amd64/amd64/apic_vector.S index a1279e6c9a85..b3ca520fd3b0 100644 --- a/sys/amd64/amd64/apic_vector.S +++ b/sys/amd64/amd64/apic_vector.S @@ -174,22 +174,6 @@ IDTVEC(xen_intr_upcall) jmp doreti #endif -#ifdef HYPERV -/* - * This is the Hyper-V vmbus channel direct callback interrupt. - * Only used when it is running on Hyper-V. - */ - .text - SUPERALIGN_TEXT -IDTVEC(hv_vmbus_callback) - PUSH_FRAME - FAKE_MCOUNT(TF_RIP(%rsp)) - movq %rsp, %rdi - call hv_vector_handler - MEXITCOUNT - jmp doreti -#endif - #ifdef SMP /* * Global address space TLB shootdown. diff --git a/sys/amd64/conf/GENERIC b/sys/amd64/conf/GENERIC index 0ed672dd8506..272da432e50e 100644 --- a/sys/amd64/conf/GENERIC +++ b/sys/amd64/conf/GENERIC @@ -350,8 +350,6 @@ device virtio_scsi # VirtIO SCSI device device virtio_balloon # VirtIO Memory Balloon device # HyperV drivers and enchancement support -# NOTE: HYPERV depends on hyperv. They must be added or removed together. -options HYPERV # Hyper-V kernel infrastructure device hyperv # HyperV drivers # Xen HVM Guest Optimizations diff --git a/sys/amd64/conf/NOTES b/sys/amd64/conf/NOTES index 3e7876aaaa44..c87ad640be1e 100644 --- a/sys/amd64/conf/NOTES +++ b/sys/amd64/conf/NOTES @@ -515,7 +515,6 @@ device virtio_random # VirtIO Entropy device device virtio_console # VirtIO Console device # Microsoft Hyper-V enchancement support -options HYPERV # Hyper-V kernel infrastructure device hyperv # HyperV drivers # Xen HVM Guest Optimizations diff --git a/sys/conf/files.amd64 b/sys/conf/files.amd64 index 85366fa9804e..ca31558119d0 100644 --- a/sys/conf/files.amd64 +++ b/sys/conf/files.amd64 @@ -277,6 +277,7 @@ dev/hyperv/vmbus/hv_hv.c optional hyperv dev/hyperv/vmbus/hv_et.c optional hyperv dev/hyperv/vmbus/hv_ring_buffer.c optional hyperv dev/hyperv/vmbus/hv_vmbus_drv_freebsd.c optional hyperv +dev/hyperv/vmbus/amd64/hv_vector.S optional hyperv dev/nfe/if_nfe.c optional nfe pci dev/ntb/if_ntb/if_ntb.c optional if_ntb dev/ntb/ntb_hw/ntb_hw.c optional if_ntb | ntb_hw diff --git a/sys/conf/files.i386 b/sys/conf/files.i386 index 4b6f158decfd..eb8585f2be02 100644 --- a/sys/conf/files.i386 +++ b/sys/conf/files.i386 @@ -252,6 +252,7 @@ dev/hyperv/vmbus/hv_hv.c optional hyperv dev/hyperv/vmbus/hv_et.c optional hyperv dev/hyperv/vmbus/hv_ring_buffer.c optional hyperv dev/hyperv/vmbus/hv_vmbus_drv_freebsd.c optional hyperv +dev/hyperv/vmbus/i386/hv_vector.S optional hyperv dev/ichwd/ichwd.c optional ichwd dev/if_ndis/if_ndis.c optional ndis dev/if_ndis/if_ndis_pccard.c optional ndis pccard diff --git a/sys/conf/options.amd64 b/sys/conf/options.amd64 index 0e591878dece..f1d4b4a57e48 100644 --- a/sys/conf/options.amd64 +++ b/sys/conf/options.amd64 @@ -63,7 +63,5 @@ BPF_JITTER opt_bpf.h XENHVM opt_global.h -HYPERV opt_global.h - # options for the Intel C600 SAS driver (isci) ISCI_LOGGING opt_isci.h diff --git a/sys/conf/options.i386 b/sys/conf/options.i386 index 69eb7e374a21..e51f82c50a4c 100644 --- a/sys/conf/options.i386 +++ b/sys/conf/options.i386 @@ -123,7 +123,5 @@ BPF_JITTER opt_bpf.h XENHVM opt_global.h -HYPERV opt_global.h - # options for the Intel C600 SAS driver (isci) ISCI_LOGGING opt_isci.h diff --git a/sys/dev/hyperv/vmbus/amd64/hv_vector.S b/sys/dev/hyperv/vmbus/amd64/hv_vector.S new file mode 100644 index 000000000000..259448388b61 --- /dev/null +++ b/sys/dev/hyperv/vmbus/amd64/hv_vector.S @@ -0,0 +1,46 @@ +/*- + * Copyright (c) 2016 Microsoft Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice unmodified, this list of conditions, and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $FreeBSD$ + */ + +#include +#include + +#include "assym.s" + +/* + * This is the Hyper-V vmbus channel direct callback interrupt. + * Only used when it is running on Hyper-V. + */ + .text + SUPERALIGN_TEXT +IDTVEC(hv_vmbus_callback) + PUSH_FRAME + FAKE_MCOUNT(TF_RIP(%rsp)) + movq %rsp, %rdi + call hv_vector_handler + MEXITCOUNT + jmp doreti diff --git a/sys/dev/hyperv/vmbus/hv_vmbus_drv_freebsd.c b/sys/dev/hyperv/vmbus/hv_vmbus_drv_freebsd.c index 44e19d26e144..ec4b26fe6fe6 100644 --- a/sys/dev/hyperv/vmbus/hv_vmbus_drv_freebsd.c +++ b/sys/dev/hyperv/vmbus/hv_vmbus_drv_freebsd.c @@ -370,9 +370,7 @@ vmbus_probe(device_t dev) { return (BUS_PROBE_DEFAULT); } -#ifdef HYPERV extern inthand_t IDTVEC(hv_vmbus_callback); -#endif /** * @brief Main vmbus driver initialization routine. @@ -406,14 +404,10 @@ vmbus_bus_init(void) return (ret); } -#ifdef HYPERV /* * Find a free IDT slot for vmbus callback. */ hv_vmbus_g_context.hv_cb_vector = lapic_ipi_alloc(IDTVEC(hv_vmbus_callback)); -#else - hv_vmbus_g_context.hv_cb_vector = -1; -#endif if (hv_vmbus_g_context.hv_cb_vector < 0) { if(bootverbose) printf("Error VMBUS: Cannot find free IDT slot for " diff --git a/sys/dev/hyperv/vmbus/i386/hv_vector.S b/sys/dev/hyperv/vmbus/i386/hv_vector.S new file mode 100644 index 000000000000..55a26130f0c1 --- /dev/null +++ b/sys/dev/hyperv/vmbus/i386/hv_vector.S @@ -0,0 +1,49 @@ +/*- + * Copyright (c) 2016 Microsoft Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice unmodified, this list of conditions, and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $FreeBSD$ + */ + +#include +#include + +#include "assym.s" + +/* + * This is the Hyper-V vmbus channel direct callback interrupt. + * Only used when it is running on Hyper-V. + */ + .text + SUPERALIGN_TEXT +IDTVEC(hv_vmbus_callback) + PUSH_FRAME + SET_KERNEL_SREGS + cld + FAKE_MCOUNT(TF_EIP(%esp)) + pushl %esp + call hv_vector_handler + add $4, %esp + MEXITCOUNT + jmp doreti diff --git a/sys/i386/conf/GENERIC b/sys/i386/conf/GENERIC index e23906dc3242..ee2df93e6543 100644 --- a/sys/i386/conf/GENERIC +++ b/sys/i386/conf/GENERIC @@ -367,8 +367,6 @@ device virtio_scsi # VirtIO SCSI device device virtio_balloon # VirtIO Memory Balloon device # HyperV drivers and enchancement support -# NOTE: HYPERV depends on hyperv. They must be added or removed together. -options HYPERV # Hyper-V kernel infrastructure device hyperv # HyperV drivers # Xen HVM Guest Optimizations diff --git a/sys/i386/i386/apic_vector.s b/sys/i386/i386/apic_vector.s index 18b3c5dc2d64..9d56b93f40bd 100644 --- a/sys/i386/i386/apic_vector.s +++ b/sys/i386/i386/apic_vector.s @@ -181,25 +181,6 @@ IDTVEC(xen_intr_upcall) jmp doreti #endif -#ifdef HYPERV -/* - * This is the Hyper-V vmbus channel direct callback interrupt. - * Only used when it is running on Hyper-V. - */ - .text - SUPERALIGN_TEXT -IDTVEC(hv_vmbus_callback) - PUSH_FRAME - SET_KERNEL_SREGS - cld - FAKE_MCOUNT(TF_EIP(%esp)) - pushl %esp - call hv_vector_handler - add $4, %esp - MEXITCOUNT - jmp doreti -#endif - #ifdef SMP /* * Global address space TLB shootdown. diff --git a/sys/modules/hyperv/vmbus/Makefile b/sys/modules/hyperv/vmbus/Makefile index 637157b3ec49..8187146ae9dc 100644 --- a/sys/modules/hyperv/vmbus/Makefile +++ b/sys/modules/hyperv/vmbus/Makefile @@ -1,7 +1,7 @@ # $FreeBSD$ .PATH: ${.CURDIR}/../../../dev/hyperv/vmbus \ - ${.CURDIR}/../../../dev/hyperv/utilities + ${.CURDIR}/../../../dev/hyperv/vmbus/${MACHINE_CPUARCH} KMOD= hv_vmbus SRCS= hv_channel.c \ @@ -14,8 +14,17 @@ SRCS= hv_channel.c \ hv_vmbus_priv.h SRCS+= acpi_if.h bus_if.h device_if.h opt_acpi.h +# XXX: for assym.s +SRCS+= opt_kstack_pages.h opt_nfs.h opt_apic.h opt_hwpmc_hooks.h opt_compat.h + +SRCS+= assym.s \ + hv_vector.S + +hv_vector.o: + ${CC} -c -x assembler-with-cpp -DLOCORE ${CFLAGS} \ + ${.IMPSRC} -o ${.TARGET} + CFLAGS+= -I${.CURDIR}/../../../dev/hyperv/include \ - -I${.CURDIR}/../../../dev/hyperv/vmbus \ - -I${.CURDIR}/../../../dev/hyperv/utilities + -I${.CURDIR}/../../../dev/hyperv/vmbus .include From da908789ee5450e0cd72ee2d3ada092e05abf1db Mon Sep 17 00:00:00 2001 From: Enji Cooper Date: Fri, 15 Apr 2016 02:36:14 +0000 Subject: [PATCH 082/143] Fix typos (intenral -> internal) in comments --- sys/cam/ata/ata_da.c | 2 +- sys/sys/module.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sys/cam/ata/ata_da.c b/sys/cam/ata/ata_da.c index 1d1d033c6833..d983a97a4015 100644 --- a/sys/cam/ata/ata_da.c +++ b/sys/cam/ata/ata_da.c @@ -913,7 +913,7 @@ adadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t len xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL); /* - * Tell the drive to flush its intenral cache. if we + * Tell the drive to flush its internal cache. if we * can't flush in 5s we have big problems. No need to * wait the default 60s to detect problems. */ diff --git a/sys/sys/module.h b/sys/sys/module.h index f0192d57b214..07464fc6e1f6 100644 --- a/sys/sys/module.h +++ b/sys/sys/module.h @@ -166,7 +166,7 @@ struct mod_pnp_match_info /** * Generic macros to create pnp info hints that modules may export - * to allow external tools to parse their intenral device tables + * to allow external tools to parse their internal device tables * to make an informed guess about what driver(s) to load. */ #define MODULE_PNP_INFO(d, b, unique, t, l, n) \ From abea2d5a7e015dce428bd2d748c81650514c5efc Mon Sep 17 00:00:00 2001 From: Enji Cooper Date: Fri, 15 Apr 2016 02:53:52 +0000 Subject: [PATCH 083/143] Set test_argv to NULL, not 0, if not executing a specific test MFC after: 1 week Submitted by: pfg Sponsored by: EMC / Isilon Storage Division --- tests/sys/file/flock_helper.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/sys/file/flock_helper.c b/tests/sys/file/flock_helper.c index 49e47b830896..0fca15e48ef2 100644 --- a/tests/sys/file/flock_helper.c +++ b/tests/sys/file/flock_helper.c @@ -1566,7 +1566,7 @@ main(int argc, const char *argv[]) } else { testnum = 0; test_argc = 0; - test_argv = 0; + test_argv = NULL; } sa.sa_handler = ignore_alarm; From 15be49f5a1bd11299c5b8f40814d5eba8aed8399 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Fri, 15 Apr 2016 03:09:55 +0000 Subject: [PATCH 084/143] Create wrappers for uint64_t and int64_t for the tunables. While not strictly necessary, it is more convenient. --- sys/kern/kern_environment.c | 46 +++++++++++++++++++++++++++++++++++++ sys/sys/kernel.h | 38 ++++++++++++++++++++++++++++++ sys/sys/systm.h | 2 ++ 3 files changed, 86 insertions(+) diff --git a/sys/kern/kern_environment.c b/sys/kern/kern_environment.c index 511ab697a525..c05c063efd57 100644 --- a/sys/kern/kern_environment.c +++ b/sys/kern/kern_environment.c @@ -544,6 +544,36 @@ getenv_uint(const char *name, unsigned int *data) return (rval); } +/* + * Return an int64_t value from an environment variable. + */ +int +getenv_int64(const char *name, int64_t *data) +{ + quad_t tmp; + int64_t rval; + + rval = getenv_quad(name, &tmp); + if (rval) + *data = (int64_t) tmp; + return (rval); +} + +/* + * Return an uint64_t value from an environment variable. + */ +int +getenv_uint64(const char *name, uint64_t *data) +{ + quad_t tmp; + uint64_t rval; + + rval = getenv_quad(name, &tmp); + if (rval) + *data = (uint64_t) tmp; + return (rval); +} + /* * Return a long value from an environment variable. */ @@ -649,6 +679,22 @@ tunable_ulong_init(void *data) TUNABLE_ULONG_FETCH(d->path, d->var); } +void +tunable_int64_init(void *data) +{ + struct tunable_int64 *d = (struct tunable_int64 *)data; + + TUNABLE_INT64_FETCH(d->path, d->var); +} + +void +tunable_uint64_init(void *data) +{ + struct tunable_uint64 *d = (struct tunable_uint64 *)data; + + TUNABLE_UINT64_FETCH(d->path, d->var); +} + void tunable_quad_init(void *data) { diff --git a/sys/sys/kernel.h b/sys/sys/kernel.h index dddf087ff15b..02628babb2c7 100644 --- a/sys/sys/kernel.h +++ b/sys/sys/kernel.h @@ -316,6 +316,44 @@ struct tunable_ulong { #define TUNABLE_ULONG_FETCH(path, var) getenv_ulong((path), (var)) +/* + * int64_t + */ +extern void tunable_int64_init(void *); +struct tunable_int64 { + const char *path; + int64_t *var; +}; +#define TUNABLE_INT64(path, var) \ + static struct tunable_int64 __CONCAT(__tunable_int64_, __LINE__) = { \ + (path), \ + (var), \ + }; \ + SYSINIT(__CONCAT(__Tunable_init_, __LINE__), \ + SI_SUB_TUNABLES, SI_ORDER_MIDDLE, tunable_int64_init, \ + &__CONCAT(__tunable_int64_, __LINE__)) + +#define TUNABLE_INT64_FETCH(path, var) getenv_int64((path), (var)) + +/* + * uint64_t + */ +extern void tunable_uint64_init(void *); +struct tunable_uint64 { + const char *path; + uint64_t *var; +}; +#define TUNABLE_UINT64(path, var) \ + static struct tunable_ulong __CONCAT(__tunable_uint64_, __LINE__) = { \ + (path), \ + (var), \ + }; \ + SYSINIT(__CONCAT(__Tunable_init_, __LINE__), \ + SI_SUB_TUNABLES, SI_ORDER_MIDDLE, tunable_uint64_init, \ + &__CONCAT(__tunable_uint64_, __LINE__)) + +#define TUNABLE_UINT64_FETCH(path, var) getenv_uint64((path), (var)) + /* * quad */ diff --git a/sys/sys/systm.h b/sys/sys/systm.h index 9c6e45082170..34ad5ba58dd8 100644 --- a/sys/sys/systm.h +++ b/sys/sys/systm.h @@ -322,6 +322,8 @@ int getenv_uint(const char *name, unsigned int *data); int getenv_long(const char *name, long *data); int getenv_ulong(const char *name, unsigned long *data); int getenv_string(const char *name, char *data, int size); +int getenv_int64(const char *name, int64_t *data); +int getenv_uint64(const char *name, uint64_t *data); int getenv_quad(const char *name, quad_t *data); int kern_setenv(const char *name, const char *value); int kern_unsetenv(const char *name); From f3bea265e199fc531e35c57d8c1191236ffee12d Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Fri, 15 Apr 2016 03:09:58 +0000 Subject: [PATCH 085/143] Use the new TUNABLE_INT64 to match the type of sbintime_t. --- sys/cam/scsi/scsi_da.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/cam/scsi/scsi_da.c b/sys/cam/scsi/scsi_da.c index 907203a24f15..8299c06a9793 100644 --- a/sys/cam/scsi/scsi_da.c +++ b/sys/cam/scsi/scsi_da.c @@ -1271,7 +1271,7 @@ SYSCTL_INT(_kern_cam_da, OID_AUTO, send_ordered, CTLFLAG_RWTUN, SYSCTL_PROC(_kern_cam_da, OID_AUTO, default_softtimeout, CTLTYPE_UINT | CTLFLAG_RW, NULL, 0, dasysctlsofttimeout, "I", "Soft I/O timeout (ms)"); -TUNABLE_LONG("kern.cam.da.default_softtimeout", &da_default_softtimeout); +TUNABLE_INT64("kern.cam.da.default_softtimeout", &da_default_softtimeout); /* * DA_ORDEREDTAG_INTERVAL determines how often, relative From 555bb680cced27f2239ffc4ae12af03e6ae285cd Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Fri, 15 Apr 2016 03:10:04 +0000 Subject: [PATCH 086/143] Add FCCT M500 to the NCQ black list. Linux added it in 4.2 (August 2015). Correct the M500 firmware versions. EU07 was the engineering test version, not the release version with the fix. MU07 is the release version. It's the only Micron firmware version to actually work. Remove support for EU07. This brings the blacklist into parity with the Linux blacklist as of 4.5, except for the Micron M500 MU07 entry. I personally tested the MU07 firmware on 12 machines running 6 drives each with no corruption in the past 6 months with Netflix production loads. Prior versions of the M500 firmware wouldn't last more than a few days. Sponsored by: Netflix, Inc. --- sys/cam/ata/ata_da.c | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/sys/cam/ata/ata_da.c b/sys/cam/ata/ata_da.c index d983a97a4015..5ead0d19bc6a 100644 --- a/sys/cam/ata/ata_da.c +++ b/sys/cam/ata/ata_da.c @@ -361,10 +361,10 @@ static struct ada_quirk_entry ada_quirk_table[] = }, { /* - * Crucial M500 SSDs EU07 firmware - * NCQ Trim works ? + * Crucial M500 SSDs MU07 firmware + * NCQ Trim works */ - { T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "EU07" }, + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "MU07" }, /*quirks*/0 }, { @@ -399,6 +399,14 @@ static struct ada_quirk_entry ada_quirk_table[] = { T_DIRECT, SIP_MEDIA_FIXED, "*", "C300-CTFDDAC???MAG*", "*" }, /*quirks*/ADA_Q_4K }, + { + /* + * FCCT M500 SSDs + * NCQ Trim doesn't work + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "FCCT*M500*", "*" }, + /*quirks*/ADA_Q_NCQ_TRIM_BROKEN + }, { /* * Intel 320 Series SSDs @@ -465,10 +473,10 @@ static struct ada_quirk_entry ada_quirk_table[] = }, { /* - * Micron M500 SSDs firmware EU07 + * Micron M500 SSDs firmware MU07 * NCQ Trim works? */ - { T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "EU07" }, + { T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "MU07" }, /*quirks*/0 }, { From 2c6167310efd894360b679d01398cc63214ca619 Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Fri, 15 Apr 2016 03:38:58 +0000 Subject: [PATCH 087/143] Use NULL instead of 0 for pointers. fopen(3) returns NULL in case it can't open the STREAM. fgetln(3) returns NULL if it can't get a line from a STREAM. malloc returns NULL if it can't allocate memory. --- usr.sbin/fmtree/excludes.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/usr.sbin/fmtree/excludes.c b/usr.sbin/fmtree/excludes.c index 21a49b04f744..9f1c56405706 100644 --- a/usr.sbin/fmtree/excludes.c +++ b/usr.sbin/fmtree/excludes.c @@ -69,10 +69,10 @@ read_excludes_file(const char *name) size_t len; fp = fopen(name, "r"); - if (fp == 0) + if (fp == NULL) err(1, "%s", name); - while ((line = fgetln(fp, &len)) != 0) { + while ((line = fgetln(fp, &len)) != NULL) { if (line[len - 1] == '\n') len--; if (len == 0) @@ -80,7 +80,7 @@ read_excludes_file(const char *name) str = malloc(len + 1); e = malloc(sizeof *e); - if (str == 0 || e == 0) + if (str == NULL || e == NULL) errx(1, "memory allocation error"); e->glob = str; memcpy(str, line, len); From 6cd99ae86d426c7006d655b182fe3ae4991d795b Mon Sep 17 00:00:00 2001 From: John Baldwin Date: Fri, 15 Apr 2016 03:42:12 +0000 Subject: [PATCH 088/143] Add a new PCI bus interface method to alloc the ivars (dinfo) for a device. The ACPI and OFW PCI bus drivers as well as CardBus override this to allocate the larger ivars to hold additional info beyond the stock PCI ivars. This removes the need to pass the size to functions like pci_add_iov_child() and pci_read_device() simplifying IOV and bus rescanning implementations. As a result of this and earlier changes, the ACPI PCI bus driver no longer needs its own device_attach and pci_create_iov_child methods but can use the methods in the stock PCI bus driver instead. Differential Revision: https://reviews.freebsd.org/D5891 --- sys/dev/acpica/acpi_pci.c | 77 +++++++++++------------------------- sys/dev/cardbus/cardbus.c | 15 ++++++- sys/dev/pci/pci.c | 62 +++++++++++++---------------- sys/dev/pci/pci_if.m | 4 ++ sys/dev/pci/pci_iov.c | 2 - sys/dev/pci/pci_private.h | 12 +++--- sys/dev/pci/pcivar.h | 1 - sys/mips/nlm/xlp_pci.c | 4 +- sys/powerpc/ofw/ofw_pcibus.c | 17 ++++++-- sys/sparc64/pci/ofw_pcibus.c | 19 +++++++-- 10 files changed, 103 insertions(+), 110 deletions(-) diff --git a/sys/dev/acpica/acpi_pci.c b/sys/dev/acpica/acpi_pci.c index 1dee131b498c..44b58044eef2 100644 --- a/sys/dev/acpica/acpi_pci.c +++ b/sys/dev/acpica/acpi_pci.c @@ -70,7 +70,7 @@ CTASSERT(ACPI_STATE_D1 == PCI_POWERSTATE_D1); CTASSERT(ACPI_STATE_D2 == PCI_POWERSTATE_D2); CTASSERT(ACPI_STATE_D3 == PCI_POWERSTATE_D3); -static int acpi_pci_attach(device_t dev); +static struct pci_devinfo *acpi_pci_alloc_devinfo(device_t dev); static void acpi_pci_child_deleted(device_t dev, device_t child); static int acpi_pci_child_location_str_method(device_t cbdev, device_t child, char *buf, size_t buflen); @@ -86,15 +86,9 @@ static int acpi_pci_set_powerstate_method(device_t dev, device_t child, static void acpi_pci_update_device(ACPI_HANDLE handle, device_t pci_child); static bus_dma_tag_t acpi_pci_get_dma_tag(device_t bus, device_t child); -#ifdef PCI_IOV -static device_t acpi_pci_create_iov_child(device_t bus, device_t pf, - uint16_t rid, uint16_t vid, uint16_t did); -#endif - static device_method_t acpi_pci_methods[] = { /* Device interface */ DEVMETHOD(device_probe, acpi_pci_probe), - DEVMETHOD(device_attach, acpi_pci_attach), /* Bus interface */ DEVMETHOD(bus_read_ivar, acpi_pci_read_ivar), @@ -105,11 +99,9 @@ static device_method_t acpi_pci_methods[] = { DEVMETHOD(bus_get_domain, acpi_get_domain), /* PCI interface */ + DEVMETHOD(pci_alloc_devinfo, acpi_pci_alloc_devinfo), DEVMETHOD(pci_child_added, acpi_pci_child_added), DEVMETHOD(pci_set_powerstate, acpi_pci_set_powerstate_method), -#ifdef PCI_IOV - DEVMETHOD(pci_create_iov_child, acpi_pci_create_iov_child), -#endif DEVMETHOD_END }; @@ -123,6 +115,15 @@ MODULE_DEPEND(acpi_pci, acpi, 1, 1, 1); MODULE_DEPEND(acpi_pci, pci, 1, 1, 1); MODULE_VERSION(acpi_pci, 1); +static struct pci_devinfo * +acpi_pci_alloc_devinfo(device_t dev) +{ + struct acpi_pci_devinfo *dinfo; + + dinfo = malloc(sizeof(*dinfo), M_DEVBUF, M_WAITOK | M_ZERO); + return (&dinfo->ap_dinfo); +} + static int acpi_pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result) { @@ -298,38 +299,6 @@ void acpi_pci_child_added(device_t dev, device_t child) { - AcpiWalkNamespace(ACPI_TYPE_DEVICE, acpi_get_handle(dev), 1, - acpi_pci_save_handle, NULL, child, NULL); -} - -static int -acpi_pci_probe(device_t dev) -{ - - if (acpi_get_handle(dev) == NULL) - return (ENXIO); - device_set_desc(dev, "ACPI PCI bus"); - return (BUS_PROBE_DEFAULT); -} - -static int -acpi_pci_attach(device_t dev) -{ - int busno, domain, error; - - error = pci_attach_common(dev); - if (error) - return (error); - - /* - * Since there can be multiple independantly numbered PCI - * busses on systems with multiple PCI domains, we can't use - * the unit number to decide which bus we are probing. We ask - * the parent pcib what our domain and bus numbers are. - */ - domain = pcib_get_domain(dev); - busno = pcib_get_bus(dev); - /* * PCI devices are added via the bus scan in the normal PCI * bus driver. As each device is added, the @@ -342,9 +311,18 @@ acpi_pci_attach(device_t dev) * pci_add_children() doesn't find. We currently just ignore * these devices. */ - pci_add_children(dev, domain, busno, sizeof(struct acpi_pci_devinfo)); + AcpiWalkNamespace(ACPI_TYPE_DEVICE, acpi_get_handle(dev), 1, + acpi_pci_save_handle, NULL, child, NULL); +} - return (bus_generic_attach(dev)); +static int +acpi_pci_probe(device_t dev) +{ + + if (acpi_get_handle(dev) == NULL) + return (ENXIO); + device_set_desc(dev, "ACPI PCI bus"); + return (BUS_PROBE_DEFAULT); } #ifdef ACPI_DMAR @@ -372,14 +350,3 @@ acpi_pci_get_dma_tag(device_t bus, device_t child) } #endif -#ifdef PCI_IOV -static device_t -acpi_pci_create_iov_child(device_t bus, device_t pf, uint16_t rid, uint16_t vid, - uint16_t did) -{ - - return (pci_add_iov_child(bus, pf, sizeof(struct acpi_pci_devinfo), rid, - vid, did)); -} -#endif - diff --git a/sys/dev/cardbus/cardbus.c b/sys/dev/cardbus/cardbus.c index e785b0f26f7d..a6037e15c1ea 100644 --- a/sys/dev/cardbus/cardbus.c +++ b/sys/dev/cardbus/cardbus.c @@ -169,6 +169,15 @@ cardbus_device_setup_regs(pcicfgregs *cfg) pci_write_config(dev, PCIR_MAXLAT, 0x14, 1); } +static struct pci_devinfo * +cardbus_alloc_devinfo(device_t dev) +{ + struct cardbus_devinfo *dinfo; + + dinfo = malloc(sizeof(*dinfo), M_DEVBUF, M_WAITOK | M_ZERO); + return (&dinfo->pci); +} + static int cardbus_attach_card(device_t cbdev) { @@ -191,8 +200,7 @@ cardbus_attach_card(device_t cbdev) struct cardbus_devinfo *dinfo; dinfo = (struct cardbus_devinfo *) - pci_read_device(brdev, domain, bus, slot, func, - sizeof(struct cardbus_devinfo)); + pci_read_device(brdev, cbdev, domain, bus, slot, func); if (dinfo == NULL) continue; if (dinfo->pci.cfg.mfdev) @@ -343,6 +351,9 @@ static device_method_t cardbus_methods[] = { DEVMETHOD(card_attach_card, cardbus_attach_card), DEVMETHOD(card_detach_card, cardbus_detach_card), + /* PCI interface */ + DEVMETHOD(pci_alloc_devinfo, cardbus_alloc_devinfo), + {0,0} }; diff --git a/sys/dev/pci/pci.c b/sys/dev/pci/pci.c index fbe9abde00c5..273ab4b1edd3 100644 --- a/sys/dev/pci/pci.c +++ b/sys/dev/pci/pci.c @@ -126,8 +126,8 @@ static int pci_remap_intr_method(device_t bus, device_t dev, static uint16_t pci_get_rid_method(device_t dev, device_t child); -static struct pci_devinfo * pci_fill_devinfo(device_t pcib, int d, int b, int s, - int f, uint16_t vid, uint16_t did, size_t size); +static struct pci_devinfo * pci_fill_devinfo(device_t pcib, device_t bus, int d, + int b, int s, int f, uint16_t vid, uint16_t did); static device_method_t pci_methods[] = { /* Device interface */ @@ -196,6 +196,7 @@ static device_method_t pci_methods[] = { DEVMETHOD(pci_msix_pba_bar, pci_msix_pba_bar_method), DEVMETHOD(pci_msix_table_bar, pci_msix_table_bar_method), DEVMETHOD(pci_get_rid, pci_get_rid_method), + DEVMETHOD(pci_alloc_devinfo, pci_alloc_devinfo_method), DEVMETHOD(pci_child_added, pci_child_added_method), #ifdef PCI_IOV DEVMETHOD(pci_iov_attach, pci_iov_attach_method), @@ -619,7 +620,7 @@ pci_hdrtypedata(device_t pcib, int b, int s, int f, pcicfgregs *cfg) /* read configuration header into pcicfgregs structure */ struct pci_devinfo * -pci_read_device(device_t pcib, int d, int b, int s, int f, size_t size) +pci_read_device(device_t pcib, device_t bus, int d, int b, int s, int f) { #define REG(n, w) PCIB_READ_CONFIG(pcib, b, s, f, n, w) uint16_t vid, did; @@ -627,19 +628,27 @@ pci_read_device(device_t pcib, int d, int b, int s, int f, size_t size) vid = REG(PCIR_VENDOR, 2); did = REG(PCIR_DEVICE, 2); if (vid != 0xffff) - return (pci_fill_devinfo(pcib, d, b, s, f, vid, did, size)); + return (pci_fill_devinfo(pcib, bus, d, b, s, f, vid, did)); return (NULL); } +struct pci_devinfo * +pci_alloc_devinfo_method(device_t dev) +{ + + return (malloc(sizeof(struct pci_devinfo), M_DEVBUF, + M_WAITOK | M_ZERO)); +} + static struct pci_devinfo * -pci_fill_devinfo(device_t pcib, int d, int b, int s, int f, uint16_t vid, - uint16_t did, size_t size) +pci_fill_devinfo(device_t pcib, device_t bus, int d, int b, int s, int f, + uint16_t vid, uint16_t did) { struct pci_devinfo *devlist_entry; pcicfgregs *cfg; - devlist_entry = malloc(size, M_DEVBUF, M_WAITOK | M_ZERO); + devlist_entry = PCI_ALLOC_DEVINFO(bus); cfg = &devlist_entry->cfg; @@ -665,7 +674,6 @@ pci_fill_devinfo(device_t pcib, int d, int b, int s, int f, uint16_t vid, cfg->hdrtype &= ~PCIM_MFDEV; STAILQ_INIT(&cfg->maps); - cfg->devinfo_size = size; cfg->iov = NULL; pci_fixancient(cfg); @@ -3854,11 +3862,11 @@ pci_add_resources(device_t bus, device_t dev, int force, uint32_t prefetchmask) static struct pci_devinfo * pci_identify_function(device_t pcib, device_t dev, int domain, int busno, - int slot, int func, size_t dinfo_size) + int slot, int func) { struct pci_devinfo *dinfo; - dinfo = pci_read_device(pcib, domain, busno, slot, func, dinfo_size); + dinfo = pci_read_device(pcib, dev, domain, busno, slot, func); if (dinfo != NULL) pci_add_child(dev, dinfo); @@ -3866,7 +3874,7 @@ pci_identify_function(device_t pcib, device_t dev, int domain, int busno, } void -pci_add_children(device_t dev, int domain, int busno, size_t dinfo_size) +pci_add_children(device_t dev, int domain, int busno) { #define REG(n, w) PCIB_READ_CONFIG(pcib, busno, s, f, n, w) device_t pcib = device_get_parent(dev); @@ -3882,8 +3890,7 @@ pci_add_children(device_t dev, int domain, int busno, size_t dinfo_size) * functions on this bus as ARI changes the set of slots and functions * that are legal on this bus. */ - dinfo = pci_identify_function(pcib, dev, domain, busno, 0, 0, - dinfo_size); + dinfo = pci_identify_function(pcib, dev, domain, busno, 0, 0); if (dinfo != NULL && pci_enable_ari) PCIB_TRY_ENABLE_ARI(pcib, dinfo->cfg.dev); @@ -3893,8 +3900,6 @@ pci_add_children(device_t dev, int domain, int busno, size_t dinfo_size) */ first_func = 1; - KASSERT(dinfo_size >= sizeof(struct pci_devinfo), - ("dinfo_size too small")); maxslots = PCIB_MAXSLOTS(pcib); for (s = 0; s <= maxslots; s++, first_func = 0) { pcifunchigh = 0; @@ -3906,16 +3911,15 @@ pci_add_children(device_t dev, int domain, int busno, size_t dinfo_size) if (hdrtype & PCIM_MFDEV) pcifunchigh = PCIB_MAXFUNCS(pcib); for (f = first_func; f <= pcifunchigh; f++) - pci_identify_function(pcib, dev, domain, busno, s, f, - dinfo_size); + pci_identify_function(pcib, dev, domain, busno, s, f); } #undef REG } #ifdef PCI_IOV device_t -pci_add_iov_child(device_t bus, device_t pf, size_t size, uint16_t rid, - uint16_t vid, uint16_t did) +pci_add_iov_child(device_t bus, device_t pf, uint16_t rid, uint16_t vid, + uint16_t did) { struct pci_devinfo *pf_dinfo, *vf_dinfo; device_t pcib; @@ -3923,23 +3927,12 @@ pci_add_iov_child(device_t bus, device_t pf, size_t size, uint16_t rid, pf_dinfo = device_get_ivars(pf); - /* - * Do a sanity check that we have been passed the correct size. If this - * test fails then likely the pci subclass hasn't implemented the - * pci_create_iov_child method like it's supposed it. - */ - if (size != pf_dinfo->cfg.devinfo_size) { - device_printf(pf, - "PCI subclass does not properly implement PCI_IOV\n"); - return (NULL); - } - pcib = device_get_parent(bus); PCIB_DECODE_RID(pcib, rid, &busno, &slot, &func); - vf_dinfo = pci_fill_devinfo(pcib, pci_get_domain(pcib), busno, slot, func, - vid, did, size); + vf_dinfo = pci_fill_devinfo(pcib, bus, pci_get_domain(pcib), busno, + slot, func, vid, did); vf_dinfo->cfg.flags |= PCICFG_VF; pci_add_child(bus, vf_dinfo); @@ -3952,8 +3945,7 @@ pci_create_iov_child_method(device_t bus, device_t pf, uint16_t rid, uint16_t vid, uint16_t did) { - return (pci_add_iov_child(bus, pf, sizeof(struct pci_devinfo), rid, vid, - did)); + return (pci_add_iov_child(bus, pf, rid, vid, did)); } #endif @@ -4050,7 +4042,7 @@ pci_attach(device_t dev) */ domain = pcib_get_domain(dev); busno = pcib_get_bus(dev); - pci_add_children(dev, domain, busno, sizeof(struct pci_devinfo)); + pci_add_children(dev, domain, busno); return (bus_generic_attach(dev)); } diff --git a/sys/dev/pci/pci_if.m b/sys/dev/pci/pci_if.m index 7049b9feefd5..da8030584538 100644 --- a/sys/dev/pci/pci_if.m +++ b/sys/dev/pci/pci_if.m @@ -213,6 +213,10 @@ METHOD uint16_t get_rid { device_t child; }; +METHOD struct pci_devinfo * alloc_devinfo { + device_t dev; +}; + METHOD void child_added { device_t dev; device_t child; diff --git a/sys/dev/pci/pci_iov.c b/sys/dev/pci/pci_iov.c index d216557e638b..287f5a20520b 100644 --- a/sys/dev/pci/pci_iov.c +++ b/sys/dev/pci/pci_iov.c @@ -600,14 +600,12 @@ pci_iov_enumerate_vfs(struct pci_devinfo *dinfo, const nvlist_t *config, device_t bus, dev, vf; struct pcicfg_iov *iov; struct pci_devinfo *vfinfo; - size_t size; int i, error; uint16_t vid, did, next_rid; iov = dinfo->cfg.iov; dev = dinfo->cfg.dev; bus = device_get_parent(dev); - size = dinfo->cfg.devinfo_size; next_rid = first_rid; vid = pci_get_vendor(dev); did = IOV_READ(dinfo, PCIR_SRIOV_VF_DID, 2); diff --git a/sys/dev/pci/pci_private.h b/sys/dev/pci/pci_private.h index e11dcfa32a20..222ffb89063a 100644 --- a/sys/dev/pci/pci_private.h +++ b/sys/dev/pci/pci_private.h @@ -48,14 +48,14 @@ struct pci_softc { extern int pci_do_power_resume; extern int pci_do_power_suspend; -void pci_add_children(device_t dev, int domain, int busno, - size_t dinfo_size); +void pci_add_children(device_t dev, int domain, int busno); void pci_add_child(device_t bus, struct pci_devinfo *dinfo); -device_t pci_add_iov_child(device_t bus, device_t pf, size_t dinfo_size, - uint16_t rid, uint16_t vid, uint16_t did); +device_t pci_add_iov_child(device_t bus, device_t pf, uint16_t rid, + uint16_t vid, uint16_t did); void pci_add_resources(device_t bus, device_t dev, int force, uint32_t prefetchmask); void pci_add_resources_ea(device_t bus, device_t dev, int alloc_iov); +struct pci_devinfo *pci_alloc_devinfo_method(device_t dev); int pci_attach_common(device_t dev); void pci_driver_added(device_t dev, driver_t *driver); int pci_ea_is_enabled(device_t dev, int rid); @@ -117,8 +117,8 @@ int pci_deactivate_resource(device_t dev, device_t child, int type, void pci_delete_resource(device_t dev, device_t child, int type, int rid); struct resource_list *pci_get_resource_list (device_t dev, device_t child); -struct pci_devinfo *pci_read_device(device_t pcib, int d, int b, int s, int f, - size_t size); +struct pci_devinfo *pci_read_device(device_t pcib, device_t bus, int d, int b, + int s, int f); void pci_print_verbose(struct pci_devinfo *dinfo); int pci_freecfg(struct pci_devinfo *dinfo); void pci_child_deleted(device_t dev, device_t child); diff --git a/sys/dev/pci/pcivar.h b/sys/dev/pci/pcivar.h index c829292f3916..8d9ea7ec02fb 100644 --- a/sys/dev/pci/pcivar.h +++ b/sys/dev/pci/pcivar.h @@ -209,7 +209,6 @@ typedef struct pcicfg { uint8_t func; /* config space function number */ uint32_t flags; /* flags defined above */ - size_t devinfo_size; /* Size of devinfo for this bus type. */ struct pcicfg_bridge bridge; /* Bridges */ struct pcicfg_pp pp; /* Power management */ diff --git a/sys/mips/nlm/xlp_pci.c b/sys/mips/nlm/xlp_pci.c index 863c6aa553cb..9e911469d086 100644 --- a/sys/mips/nlm/xlp_pci.c +++ b/sys/mips/nlm/xlp_pci.c @@ -125,8 +125,8 @@ xlp_pci_attach(device_t dev) XLP_PCI_DEVSCRATCH_REG0 << 2, (1 << 8) | irq, 4); } - dinfo = pci_read_device(pcib, pcib_get_domain(dev), - busno, s, f, sizeof(*dinfo)); + dinfo = pci_read_device(pcib, dev, pcib_get_domain(dev), + busno, s, f); pci_add_child(dev, dinfo); } } diff --git a/sys/powerpc/ofw/ofw_pcibus.c b/sys/powerpc/ofw/ofw_pcibus.c index 4ce6e736348f..01e2343ebca6 100644 --- a/sys/powerpc/ofw/ofw_pcibus.c +++ b/sys/powerpc/ofw/ofw_pcibus.c @@ -59,6 +59,7 @@ typedef uint32_t ofw_pci_intr_t; /* Methods */ static device_probe_t ofw_pcibus_probe; static device_attach_t ofw_pcibus_attach; +static pci_alloc_devinfo_t ofw_pcibus_alloc_devinfo; static pci_assign_interrupt_t ofw_pcibus_assign_interrupt; static ofw_bus_get_devinfo_t ofw_pcibus_get_devinfo; static bus_child_deleted_t ofw_pcibus_child_deleted; @@ -78,6 +79,7 @@ static device_method_t ofw_pcibus_methods[] = { DEVMETHOD(bus_child_pnpinfo_str, ofw_pcibus_child_pnpinfo_str_method), /* PCI interface */ + DEVMETHOD(pci_alloc_devinfo, ofw_pcibus_alloc_devinfo), DEVMETHOD(pci_assign_interrupt, ofw_pcibus_assign_interrupt), /* ofw_bus interface */ @@ -144,6 +146,15 @@ ofw_pcibus_attach(device_t dev) return (bus_generic_attach(dev)); } +struct pci_devinfo * +ofw_pcibus_alloc_devinfo(device_t dev) +{ + struct ofw_pcibus_devinfo *dinfo; + + dinfo = malloc(sizeof(*dinfo), M_DEVBUF, M_WAITOK | M_ZERO); + return (&dinfo->opd_dinfo); +} + static void ofw_pcibus_enum_devtree(device_t dev, u_int domain, u_int busno) { @@ -185,8 +196,8 @@ ofw_pcibus_enum_devtree(device_t dev, u_int domain, u_int busno) * to the PCI bus. */ - dinfo = (struct ofw_pcibus_devinfo *)pci_read_device(pcib, - domain, busno, slot, func, sizeof(*dinfo)); + dinfo = (struct ofw_pcibus_devinfo *)pci_read_device(pcib, dev, + domain, busno, slot, func); if (dinfo == NULL) continue; if (ofw_bus_gen_setup_devinfo(&dinfo->opd_obdinfo, child) != @@ -244,7 +255,7 @@ ofw_pcibus_enum_bus(device_t dev, u_int domain, u_int busno) continue; dinfo = (struct ofw_pcibus_devinfo *)pci_read_device( - pcib, domain, busno, s, f, sizeof(*dinfo)); + pcib, dev, domain, busno, s, f); if (dinfo == NULL) continue; diff --git a/sys/sparc64/pci/ofw_pcibus.c b/sys/sparc64/pci/ofw_pcibus.c index 08ffa5d69b87..11f19cf93e5a 100644 --- a/sys/sparc64/pci/ofw_pcibus.c +++ b/sys/sparc64/pci/ofw_pcibus.c @@ -70,6 +70,7 @@ static bus_child_pnpinfo_str_t ofw_pcibus_pnpinfo_str; static device_attach_t ofw_pcibus_attach; static device_probe_t ofw_pcibus_probe; static ofw_bus_get_devinfo_t ofw_pcibus_get_devinfo; +static pci_alloc_devinfo_t ofw_pcibus_alloc_devinfo; static pci_assign_interrupt_t ofw_pcibus_assign_interrupt; static device_method_t ofw_pcibus_methods[] = { @@ -82,6 +83,7 @@ static device_method_t ofw_pcibus_methods[] = { DEVMETHOD(bus_child_pnpinfo_str, ofw_pcibus_pnpinfo_str), /* PCI interface */ + DEVMETHOD(pci_alloc_devinfo, ofw_pcibus_alloc_devinfo), DEVMETHOD(pci_assign_interrupt, ofw_pcibus_assign_interrupt), /* ofw_bus interface */ @@ -250,8 +252,8 @@ ofw_pcibus_attach(device_t dev) if (strcmp(device_get_name(device_get_parent(pcib)), "nexus") == 0 && ofw_bus_get_type(pcib) != NULL && strcmp(ofw_bus_get_type(pcib), OFW_TYPE_PCIE) != 0 && - (dinfo = (struct ofw_pcibus_devinfo *)pci_read_device(pcib, - domain, busno, 0, 0, sizeof(*dinfo))) != NULL) { + (dinfo = (struct ofw_pcibus_devinfo *)pci_read_device(pcib, dev, + domain, busno, 0, 0)) != NULL) { if (ofw_bus_gen_setup_devinfo(&dinfo->opd_obdinfo, node) != 0) pci_freecfg((struct pci_devinfo *)dinfo); else @@ -270,8 +272,8 @@ ofw_pcibus_attach(device_t dev) if (pci_find_dbsf(domain, busno, slot, func) != NULL) continue; ofw_pcibus_setup_device(pcib, clock, busno, slot, func); - dinfo = (struct ofw_pcibus_devinfo *)pci_read_device(pcib, - domain, busno, slot, func, sizeof(*dinfo)); + dinfo = (struct ofw_pcibus_devinfo *)pci_read_device(pcib, dev, + domain, busno, slot, func); if (dinfo == NULL) continue; if (ofw_bus_gen_setup_devinfo(&dinfo->opd_obdinfo, child) != @@ -286,6 +288,15 @@ ofw_pcibus_attach(device_t dev) return (bus_generic_attach(dev)); } +struct pci_devinfo * +ofw_pcibus_alloc_devinfo(device_t dev) +{ + struct ofw_pcibus_devinfo *dinfo; + + dinfo = malloc(sizeof(*dinfo), M_DEVBUF, M_WAITOK | M_ZERO); + return (&dinfo->opd_dinfo); +} + static int ofw_pcibus_assign_interrupt(device_t dev, device_t child) { From ff34412a50af69ed5f3ca5538d7d2e49d2e5028b Mon Sep 17 00:00:00 2001 From: Cy Schubert Date: Fri, 15 Apr 2016 03:43:16 +0000 Subject: [PATCH 089/143] Use NULL instead of 0 for pointer comparison. MFC after: 4 weeks --- contrib/ipfilter/bpf_filter.c | 6 +++--- sys/contrib/ipfilter/netinet/ip_fil_freebsd.c | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/contrib/ipfilter/bpf_filter.c b/contrib/ipfilter/bpf_filter.c index d75570e29267..bd465761a34e 100644 --- a/contrib/ipfilter/bpf_filter.c +++ b/contrib/ipfilter/bpf_filter.c @@ -132,7 +132,7 @@ m_xword(m, k, err) return EXTRACT_LONG(cp); } m0 = m->m_next; - if (m0 == 0 || M_LEN(m0) + len - k < 4) + if (m0 == NULL || M_LEN(m0) + len - k < 4) goto bad; *err = 0; np = MTOD(m0, u_char *); @@ -168,7 +168,7 @@ m_xhalf(m, k, err) return EXTRACT_SHORT(cp); } m0 = m->m_next; - if (m0 == 0) + if (m0 == NULL) goto bad; *err = 0; return (cp[0] << 8) | MTOD(m0, u_char *)[0]; @@ -205,7 +205,7 @@ bpf_filter(pc, p, wirelen, buflen) } else m = NULL; - if (pc == 0) + if (pc == NULL) /* * No filter means accept all. */ diff --git a/sys/contrib/ipfilter/netinet/ip_fil_freebsd.c b/sys/contrib/ipfilter/netinet/ip_fil_freebsd.c index 3b74f8cf982d..2796055da1fb 100644 --- a/sys/contrib/ipfilter/netinet/ip_fil_freebsd.c +++ b/sys/contrib/ipfilter/netinet/ip_fil_freebsd.c @@ -738,7 +738,7 @@ ipf_fastroute(m0, mpp, fin, fdp) */ if (M_WRITABLE(m) == 0) { m0 = m_dup(m, M_NOWAIT); - if (m0 != 0) { + if (m0 != NULL) { FREE_MB_T(m); m = m0; *mpp = m; @@ -885,7 +885,7 @@ ipf_fastroute(m0, mpp, fin, fdp) #else MGET(m, M_NOWAIT, MT_HEADER); #endif - if (m == 0) { + if (m == NULL) { m = m0; error = ENOBUFS; goto bad; From 4bb37cd3af5a015a23f4505fd0f2cf63cbe7b9bf Mon Sep 17 00:00:00 2001 From: Cy Schubert Date: Fri, 15 Apr 2016 03:45:09 +0000 Subject: [PATCH 090/143] Static pointers need not be initialized. MFC after: 4 weeks --- contrib/ipfilter/mli_ipl.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contrib/ipfilter/mli_ipl.c b/contrib/ipfilter/mli_ipl.c index 2a0024cb459b..ccedf768e7a7 100644 --- a/contrib/ipfilter/mli_ipl.c +++ b/contrib/ipfilter/mli_ipl.c @@ -64,9 +64,9 @@ ipfrwlock_t ipf_global, ipf_mutex, ipf_ipidfrag, ipf_frcache, ipf_tokens; int (*ipf_checkp) __P((struct ip *, int, void *, int, mb_t **)); #ifdef IPFILTER_LKM -static int *ipff_addr = 0; +static int *ipff_addr; static int ipff_value; -static __psunsigned_t *ipfk_addr = 0; +static __psunsigned_t *ipfk_addr; static __psunsigned_t ipfk_code[4]; #endif static void nifattach(); @@ -85,7 +85,7 @@ typedef struct nif { int nf_unit; } nif_t; -static nif_t *nif_head = 0; +static nif_t *nif_head; static int nif_interfaces = 0; extern int in_interfaces; #if IRIX >= 60500 From 71866e627eefe32eed8033501f5f67c85c74a11a Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Fri, 15 Apr 2016 03:50:33 +0000 Subject: [PATCH 091/143] Use NULL instead of 0 for pointers. getenv(3) returns NULL if the variable name is not in the current environment. getservent(3) returns NULL on EOF or error MFC after: 4 weeks --- usr.sbin/ppp/command.c | 2 +- usr.sbin/ppp/filter.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/usr.sbin/ppp/command.c b/usr.sbin/ppp/command.c index e90d96b22b33..d0664e82e46e 100644 --- a/usr.sbin/ppp/command.c +++ b/usr.sbin/ppp/command.c @@ -651,7 +651,7 @@ ShellCommand(struct cmdargs const *arg, int bg) if ((shpid = fork()) == 0) { int i, fd; - if ((shell = getenv("SHELL")) == 0) + if ((shell = getenv("SHELL")) == NULL) shell = _PATH_BSHELL; timer_TermService(); diff --git a/usr.sbin/ppp/filter.c b/usr.sbin/ppp/filter.c index f59848e0d1d6..af5691b42db9 100644 --- a/usr.sbin/ppp/filter.c +++ b/usr.sbin/ppp/filter.c @@ -80,7 +80,7 @@ ParsePort(const char *service, const char *proto) int port; servent = getservbyname(service, proto); - if (servent != 0) + if (servent != NULL) return ntohs(servent->s_port); port = strtol(service, &cp, 0); From b9165344966975aff9ff30176418ed90f80373b2 Mon Sep 17 00:00:00 2001 From: Marcelo Araujo Date: Fri, 15 Apr 2016 04:10:47 +0000 Subject: [PATCH 092/143] Use NULL instead of 0 for pointers. fgetln(3) will returns NULL if cannot get a line from a stream. strsep(3) it will returns NULL if the end of the string was reached. jemalloc(3) malloc will returns NULL if it cannot allocate memory. fgetln(3) it will returns NULL if it cannot get a line from a stream. MFC after: 4 weeks --- usr.sbin/tzsetup/tzsetup.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/usr.sbin/tzsetup/tzsetup.c b/usr.sbin/tzsetup/tzsetup.c index fc803646c23a..e571d1f4751f 100644 --- a/usr.sbin/tzsetup/tzsetup.c +++ b/usr.sbin/tzsetup/tzsetup.c @@ -344,7 +344,7 @@ read_iso3166_table(void) err(1, "%s", path_iso3166); lineno = 0; - while ((s = fgetln(fp, &len)) != 0) { + while ((s = fgetln(fp, &len)) != NULL) { lineno++; if (s[len - 1] != '\n') errx(1, "%s:%d: invalid format", path_iso3166, lineno); @@ -354,7 +354,7 @@ read_iso3166_table(void) /* Isolate the two-letter code. */ t = strsep(&s, "\t"); - if (t == 0 || strlen(t) != 2) + if (t == NULL || strlen(t) != 2) errx(1, "%s:%d: invalid format", path_iso3166, lineno); if (t[0] < 'A' || t[0] > 'Z' || t[1] < 'A' || t[1] > 'Z') errx(1, "%s:%d: invalid code `%s'", path_iso3166, @@ -362,10 +362,10 @@ read_iso3166_table(void) /* Now skip past the three-letter and numeric codes. */ name = strsep(&s, "\t"); /* 3-let */ - if (name == 0 || strlen(name) != 3) + if (name == NULL || strlen(name) != 3) errx(1, "%s:%d: invalid format", path_iso3166, lineno); name = strsep(&s, "\t"); /* numeric */ - if (name == 0 || strlen(name) != 3) + if (name == NULL || strlen(name) != 3) errx(1, "%s:%d: invalid format", path_iso3166, lineno); name = s; @@ -407,7 +407,7 @@ add_zone_to_country(int lineno, const char *tlc, const char *descr, path_zonetab, lineno); zp = malloc(sizeof(*zp)); - if (zp == 0) + if (zp == NULL) errx(1, "malloc(%zu)", sizeof(*zp)); if (cp->nzones == 0) @@ -483,7 +483,7 @@ read_zones(void) err(1, "%s", path_zonetab); lineno = 0; - while ((line = fgetln(fp, &len)) != 0) { + while ((line = fgetln(fp, &len)) != NULL) { lineno++; if (line[len - 1] != '\n') errx(1, "%s:%d: invalid format", path_zonetab, lineno); @@ -498,7 +498,7 @@ read_zones(void) /* coord = */ strsep(&line, "\t"); /* Unused */ file = strsep(&line, "\t"); p = strchr(file, '/'); - if (p == 0) + if (p == NULL) errx(1, "%s:%d: invalid zone name `%s'", path_zonetab, lineno, file); contbuf[0] = '\0'; @@ -558,7 +558,7 @@ make_menus(void) continent_names[i].continent->menu = malloc(sizeof(dialogMenuItem) * continent_names[i].continent->nitems); - if (continent_names[i].continent->menu == 0) + if (continent_names[i].continent->menu == NULL) errx(1, "malloc for continent menu"); continent_names[i].continent->nitems = 0; continents[i].prompt = continent_items[i].prompt; From a17433653c2af9ed0c6c905e61c304a4efda2a29 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Fri, 15 Apr 2016 04:45:37 +0000 Subject: [PATCH 093/143] Add update. --- UPDATING | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/UPDATING b/UPDATING index ac92b784f6e3..dcff31551e0d 100644 --- a/UPDATING +++ b/UPDATING @@ -32,11 +32,31 @@ NOTE TO PEOPLE WHO THINK THAT FreeBSD 11.x IS SLOW: "ln -s 'abort:false,junk:false' /etc/malloc.conf".) 20160414: - The CAM I/O scheduler has been committed to the kernel. There should - be no user visible impact. This does enable NCQ Trim on ada - SSDs. While the list of known rogues that claim support for - this but actually corrupt data is believed to be complete, be - on the lookout for data corruption. + The CAM I/O scheduler has been committed to the kernel. There should be + no user visible impact. This does enable NCQ Trim on ada SSDs. While the + list of known rogues that claim support for this but actually corrupt + data is believed to be complete, be on the lookout for data + corruption. The known rogue list is believed to be complete: + + o Crucial MX100, M550 drives with MU01 firmware. + o Micron M510 and M550 drives with MU01 firmware. + o Micron M500 prior to MU07 firmware + o Samsung 830, 840, and 850 all firmwares + o FCCT M500 all firmwares + + Crucial has firmware http://www.crucial.com/usa/en/support-ssd-firmware + with working NCQ TRIM. For Micron branded drives, see your sales rep for + updated firmware. Black listed drives will work correctly because these + drives work correctly so long as no NCQ TRIMs are sent to them. Given + this list is the same as found in Linux, it's believed there are no + other rogues in the market place. All other models from the above + vendors work. + + To be safe, if you are at all concerned, you can quirk each of your + drives to prevent NCQ from being sent by setting: + kern.cam.ada.X.quirks="0x2" + in loader.conf. If the drive requires the 4k sector quirk, set the + quirks entry to 0x3. 20160330: The FAST_DEPEND build option has been removed and its functionality is From b93ecd35e7bcd7df6e73fcf4644c2a610db7a459 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Fri, 15 Apr 2016 05:10:31 +0000 Subject: [PATCH 094/143] Out of an abundance of caution treat * Samsung 843T Series SSDs (MZ7WD*) * Samsung PM851 Series SSDs (MZ7TE*) * Samsung PM853T Series SSDs (MZ7GE*) as known having broken NCQ TRIM support as they appear to be based on the same controller technology as the 840 and 850 series. I've had at least one report of the PM853 being broken, so err on the side of caution for the above drives. The PM863/SM863 appears to be based on a newer controller, so give it the benefit of the doubt. --- sys/cam/ata/ata_da.c | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/sys/cam/ata/ata_da.c b/sys/cam/ata/ata_da.c index 5ead0d19bc6a..a2025ef07069 100644 --- a/sys/cam/ata/ata_da.c +++ b/sys/cam/ata/ata_da.c @@ -567,16 +567,24 @@ static struct ada_quirk_entry ada_quirk_table[] = { T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 850*", "*" }, /*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN }, + { + /* + * Samsung SM863 Series SSDs (MZ7KM*) + * 4k optimised, NCQ believed to be working + */ + { T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7KM*", "*" }, + /*quirks*/ADA_Q_4K + }, { /* * Samsung 843T Series SSDs (MZ7WD*) * Samsung PM851 Series SSDs (MZ7TE*) * Samsung PM853T Series SSDs (MZ7GE*) - * Samsung SM863 Series SSDs (MZ7KM*) - * 4k optimised, NCQ Trim believed working + * 4k optimised, NCQ believed to be broken since these are + * appear to be built with the same controllers as the 840/850. */ { T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7*", "*" }, - /*quirks*/ADA_Q_4K + /*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN }, { /* From 5ede5b8cb54b1c369cdd20d3cd84d7dda03123a3 Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Fri, 15 Apr 2016 05:10:32 +0000 Subject: [PATCH 095/143] Put function only used by CAM_NETFLIX_IOSCHED under that ifdef. --- sys/cam/cam_iosched.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sys/cam/cam_iosched.c b/sys/cam/cam_iosched.c index b26eeac00ac8..8e78663f880b 100644 --- a/sys/cam/cam_iosched.c +++ b/sys/cam/cam_iosched.c @@ -625,9 +625,11 @@ cam_iosched_cl_maybe_steer(struct control_loop *clp) /* Periph drivers set these flags to indicate work */ #define CAM_IOSCHED_FLAG_WORK_FLAGS ((0xffffu) << 16) +#ifdef CAM_NETFLIX_IOSCHED static void cam_iosched_io_metric_update(struct cam_iosched_softc *isc, sbintime_t sim_latency, int cmd, size_t size); +#endif static inline int cam_iosched_has_flagged_work(struct cam_iosched_softc *isc) @@ -1522,6 +1524,7 @@ cam_iosched_update(struct iop_stats *iop, sbintime_t sim_latency) iop->sd = (int64_t)var < 0 ? 0 : isqrt64(var); } +#ifdef CAM_NETFLIX_IOSCHED static void cam_iosched_io_metric_update(struct cam_iosched_softc *isc, sbintime_t sim_latency, int cmd, size_t size) @@ -1541,6 +1544,7 @@ cam_iosched_io_metric_update(struct cam_iosched_softc *isc, break; } } +#endif #ifdef DDB static int biolen(struct bio_queue_head *bq) From acfc9b6862b74205ad351e87b86701c54a8d4a5f Mon Sep 17 00:00:00 2001 From: Warner Losh Date: Fri, 15 Apr 2016 05:10:39 +0000 Subject: [PATCH 096/143] Expand CAM_IO_STATS #ifdef to logical unit. --- sys/cam/ata/ata_da.c | 6 ++---- sys/cam/scsi/scsi_da.c | 6 ++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/sys/cam/ata/ata_da.c b/sys/cam/ata/ata_da.c index a2025ef07069..05134d78addc 100644 --- a/sys/cam/ata/ata_da.c +++ b/sys/cam/ata/ata_da.c @@ -2175,6 +2175,7 @@ adadone(struct cam_periph *periph, union ccb *done_ccb) static int adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags) { +#ifdef CAM_IO_STATS struct ada_softc *softc; struct cam_periph *periph; @@ -2183,9 +2184,7 @@ adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags) switch (ccb->ccb_h.status & CAM_STATUS_MASK) { case CAM_CMD_TIMEOUT: -#ifdef CAM_IO_STATS softc->timeouts++; -#endif break; case CAM_REQ_ABORTED: case CAM_REQ_CMP_ERR: @@ -2193,13 +2192,12 @@ adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags) case CAM_UNREC_HBA_ERROR: case CAM_DATA_RUN_ERR: case CAM_ATA_STATUS_ERROR: -#ifdef CAM_IO_STATS softc->errors++; -#endif break; default: break; } +#endif return(cam_periph_error(ccb, cam_flags, sense_flags, NULL)); } diff --git a/sys/cam/scsi/scsi_da.c b/sys/cam/scsi/scsi_da.c index 8299c06a9793..d97e99d9308f 100644 --- a/sys/cam/scsi/scsi_da.c +++ b/sys/cam/scsi/scsi_da.c @@ -3773,24 +3773,22 @@ daerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags) if (error == ERESTART) return (ERESTART); +#ifdef CAM_IO_STATS switch (ccb->ccb_h.status & CAM_STATUS_MASK) { case CAM_CMD_TIMEOUT: -#ifdef CAM_IO_STATS softc->timeouts++; -#endif break; case CAM_REQ_ABORTED: case CAM_REQ_CMP_ERR: case CAM_REQ_TERMIO: case CAM_UNREC_HBA_ERROR: case CAM_DATA_RUN_ERR: -#ifdef CAM_IO_STATS softc->errors++; -#endif break; default: break; } +#endif /* * XXX From 97c4992c895574e3c4d27ce0f726f98e5d4cda10 Mon Sep 17 00:00:00 2001 From: Sepherosa Ziehau Date: Fri, 15 Apr 2016 07:39:43 +0000 Subject: [PATCH 097/143] hyperv/stor: Temporary disable the wrongly done command timeout. It will be reenabled once the request processing is corrected. MFC after: 1 week Sponsored by: Microsoft OSTC --- sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c b/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c index 38f2f28461ab..b869c86d3ca1 100644 --- a/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c +++ b/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c @@ -1259,6 +1259,7 @@ storvsc_timeout_test(struct hv_storvsc_request *reqp, } #endif /* HVS_TIMEOUT_TEST */ +#ifdef notyet /** * @brief timeout handler for requests * @@ -1306,6 +1307,7 @@ storvsc_timeout(void *arg) storvsc_timeout_test(reqp, MODE_SELECT_10, 1); #endif } +#endif /** * @brief StorVSC device poll function @@ -1458,6 +1460,7 @@ storvsc_action(struct cam_sim *sim, union ccb *ccb) return; } +#ifdef notyet if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) { callout_init(&reqp->callout, 1); callout_reset_sbt(&reqp->callout, @@ -1477,6 +1480,7 @@ storvsc_action(struct cam_sim *sim, union ccb *ccb) } #endif /* HVS_TIMEOUT_TEST */ } +#endif if ((res = hv_storvsc_io_request(sc->hs_dev, reqp)) != 0) { xpt_print(ccb->ccb_h.path, @@ -2024,6 +2028,7 @@ storvsc_io_done(struct hv_storvsc_request *reqp) mtx_unlock(&sc->hs_lock); } +#ifdef notyet /* * callout_drain() will wait for the timer handler to finish * if it is running. So we don't need any lock to synchronize @@ -2034,6 +2039,7 @@ storvsc_io_done(struct hv_storvsc_request *reqp) if (ccb->ccb_h.timeout != CAM_TIME_INFINITY) { callout_drain(&reqp->callout); } +#endif ccb->ccb_h.status &= ~CAM_SIM_QUEUED; ccb->ccb_h.status &= ~CAM_STATUS_MASK; From 4a060c8407b00bb0729d72c8fef5ca44d2f3ade7 Mon Sep 17 00:00:00 2001 From: Sepherosa Ziehau Date: Fri, 15 Apr 2016 07:48:41 +0000 Subject: [PATCH 098/143] hyperv/vmbus: Put multi-channel offer logging under bootverbose Suggested by: Dexuan Cui MFC after: 1 week Sponsored by: Microsoft OSTC --- sys/dev/hyperv/vmbus/hv_channel_mgmt.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/sys/dev/hyperv/vmbus/hv_channel_mgmt.c b/sys/dev/hyperv/vmbus/hv_channel_mgmt.c index 42d3750a24f1..00941874567a 100644 --- a/sys/dev/hyperv/vmbus/hv_channel_mgmt.c +++ b/sys/dev/hyperv/vmbus/hv_channel_mgmt.c @@ -219,10 +219,14 @@ vmbus_channel_process_offer(hv_vmbus_channel *new_channel) sc_list_entry); mtx_unlock(&channel->sc_lock); + if (bootverbose) { + printf("VMBUS get multi-channel offer, " + "rel=%u, sub=%u\n", + new_channel->offer_msg.child_rel_id, + new_channel->offer_msg.offer.sub_channel_index); + } + /* Insert new channel into channel_anchor. */ - printf("VMBUS get multi-channel offer, rel=%u,sub=%u\n", - new_channel->offer_msg.child_rel_id, - new_channel->offer_msg.offer.sub_channel_index); mtx_lock(&hv_vmbus_g_connection.channel_lock); TAILQ_INSERT_TAIL(&hv_vmbus_g_connection.channel_anchor, new_channel, list_entry); From a014f7e1a6eb5cce5449dee59c014b1dc32950bf Mon Sep 17 00:00:00 2001 From: Sepherosa Ziehau Date: Fri, 15 Apr 2016 08:01:07 +0000 Subject: [PATCH 099/143] hyperv/stor: Use xpt_done_direct() upon I/O completion Reviewed by: mav MFC after: 1 week Sponsored by: Microsoft OSTC Differential Revision: https://reviews.freebsd.org/D5955 --- sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c b/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c index b869c86d3ca1..b416744d3566 100644 --- a/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c +++ b/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c @@ -2093,8 +2093,9 @@ storvsc_io_done(struct hv_storvsc_request *reqp) reqp->softc->hs_frozen = 0; } storvsc_free_request(sc, reqp); - xpt_done(ccb); mtx_unlock(&sc->hs_lock); + + xpt_done_direct(ccb); } /** From 5f9b92f8652b8c6fa0f57dffca5de56e3bd45199 Mon Sep 17 00:00:00 2001 From: Sepherosa Ziehau Date: Fri, 15 Apr 2016 08:08:46 +0000 Subject: [PATCH 100/143] hyperv: No need to zero out softc MFC after: 1 week Sponsored by: Microsoft OSTC --- sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c | 1 - sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c | 2 -- 2 files changed, 3 deletions(-) diff --git a/sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c b/sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c index 933f4543d4ad..e2ffd4379f91 100644 --- a/sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c +++ b/sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c @@ -419,7 +419,6 @@ netvsc_attach(device_t dev) sc = device_get_softc(dev); - bzero(sc, sizeof(hn_softc_t)); sc->hn_unit = unit; sc->hn_dev = dev; diff --git a/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c b/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c index b416744d3566..10d513c991ba 100644 --- a/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c +++ b/sys/dev/hyperv/storvsc/hv_storvsc_drv_freebsd.c @@ -981,8 +981,6 @@ storvsc_attach(device_t dev) goto cleanup; } - bzero(sc, sizeof(struct storvsc_softc)); - /* fill in driver specific properties */ sc->hs_drv_props = &g_drv_props_table[stor_type]; From 8310528673f24f21031d49ffdd544f8b9368e35f Mon Sep 17 00:00:00 2001 From: Sepherosa Ziehau Date: Fri, 15 Apr 2016 08:17:55 +0000 Subject: [PATCH 101/143] hyperv/hn: Hide ring to channel linkage message under bootverbose Suggested by: Dexuan Cui MFC after: 1 week Sponsored by: Microsoft OSTC --- sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c b/sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c index e2ffd4379f91..153f9c342604 100644 --- a/sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c +++ b/sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c @@ -2808,8 +2808,10 @@ hn_channel_attach(struct hn_softc *sc, struct hv_vmbus_channel *chan) rxr->hn_rx_flags |= HN_RX_FLAG_ATTACHED; chan->hv_chan_rxr = rxr; - if_printf(sc->hn_ifp, "link RX ring %d to channel%u\n", - idx, chan->offer_msg.child_rel_id); + if (bootverbose) { + if_printf(sc->hn_ifp, "link RX ring %d to channel%u\n", + idx, chan->offer_msg.child_rel_id); + } if (idx < sc->hn_tx_ring_inuse) { struct hn_tx_ring *txr = &sc->hn_tx_ring[idx]; @@ -2820,8 +2822,10 @@ hn_channel_attach(struct hn_softc *sc, struct hv_vmbus_channel *chan) chan->hv_chan_txr = txr; txr->hn_chan = chan; - if_printf(sc->hn_ifp, "link TX ring %d to channel%u\n", - idx, chan->offer_msg.child_rel_id); + if (bootverbose) { + if_printf(sc->hn_ifp, "link TX ring %d to channel%u\n", + idx, chan->offer_msg.child_rel_id); + } } /* Bind channel to a proper CPU */ From 16952e289fd52b5b717580723e4773f98e31a125 Mon Sep 17 00:00:00 2001 From: Konstantin Belousov Date: Fri, 15 Apr 2016 09:13:01 +0000 Subject: [PATCH 102/143] Avoid NULL pointer dereference, for a process which is not (yet) a member of a process group, e.g. during the system bootstrap. Submitted by: Mark Cave-Ayland MFC after: 1 week --- sys/ddb/db_ps.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sys/ddb/db_ps.c b/sys/ddb/db_ps.c index 76ab2c586240..e20b3636bdbb 100644 --- a/sys/ddb/db_ps.c +++ b/sys/ddb/db_ps.c @@ -184,7 +184,8 @@ db_ps(db_expr_t addr, bool hasaddr, db_expr_t count, char *modif) strlcat(state, "V", sizeof(state)); if (p->p_flag & P_SYSTEM || p->p_lock > 0) strlcat(state, "L", sizeof(state)); - if (p->p_session != NULL && SESS_LEADER(p)) + if (p->p_pgrp != NULL && p->p_session != NULL && + SESS_LEADER(p)) strlcat(state, "s", sizeof(state)); /* Cheated here and didn't compare pgid's. */ if (p->p_flag & P_CONTROLT) From 9b44287ce57e5541baee7a6960fcdc5cc95e601a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roger=20Pau=20Monn=C3=A9?= Date: Fri, 15 Apr 2016 09:21:50 +0000 Subject: [PATCH 103/143] busdma/bounce: revert r292255 Revert r292255 because it can create bounced regions without contiguous page offsets, which is needed for USB devices. Another solution would be to force bouncing the full buffer always (even when only one page requires bouncing), but this seems overly complicated and unnecessary, and it will probably involve using more bounce pages than the current code. Reported by: phk --- sys/x86/x86/busdma_bounce.c | 56 +++++++++++++++++++++++++++++-------- 1 file changed, 44 insertions(+), 12 deletions(-) diff --git a/sys/x86/x86/busdma_bounce.c b/sys/x86/x86/busdma_bounce.c index 6e9aa70e5292..78d04b94f0de 100644 --- a/sys/x86/x86/busdma_bounce.c +++ b/sys/x86/x86/busdma_bounce.c @@ -476,7 +476,8 @@ _bus_dmamap_count_phys(bus_dma_tag_t dmat, bus_dmamap_t map, vm_paddr_t buf, while (buflen != 0) { sgsize = MIN(buflen, dmat->common.maxsegsz); if (bus_dma_run_filter(&dmat->common, curaddr)) { - sgsize = MIN(PAGE_SIZE, sgsize); + sgsize = MIN(sgsize, + PAGE_SIZE - (curaddr & PAGE_MASK)); map->pagesneeded++; } curaddr += sgsize; @@ -516,7 +517,8 @@ _bus_dmamap_count_pages(bus_dma_tag_t dmat, bus_dmamap_t map, pmap_t pmap, else paddr = pmap_extract(pmap, vaddr); if (bus_dma_run_filter(&dmat->common, paddr) != 0) { - sg_len = PAGE_SIZE; + sg_len = roundup2(sg_len, + dmat->common.alignment); map->pagesneeded++; } vaddr += sg_len; @@ -552,7 +554,9 @@ _bus_dmamap_count_ma(bus_dma_tag_t dmat, bus_dmamap_t map, struct vm_page **ma, max_sgsize = MIN(buflen, dmat->common.maxsegsz); sg_len = MIN(sg_len, max_sgsize); if (bus_dma_run_filter(&dmat->common, paddr) != 0) { - sg_len = MIN(PAGE_SIZE, max_sgsize); + sg_len = roundup2(sg_len, + dmat->common.alignment); + sg_len = MIN(sg_len, max_sgsize); KASSERT((sg_len & (dmat->common.alignment - 1)) == 0, ("Segment size is not aligned")); map->pagesneeded++; @@ -648,7 +652,7 @@ bounce_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, int *segp) { bus_size_t sgsize; - bus_addr_t curaddr, nextaddr; + bus_addr_t curaddr; int error; if (map == NULL) @@ -672,12 +676,9 @@ bounce_bus_dmamap_load_phys(bus_dma_tag_t dmat, bus_dmamap_t map, if (((dmat->bounce_flags & BUS_DMA_COULD_BOUNCE) != 0) && map->pagesneeded != 0 && bus_dma_run_filter(&dmat->common, curaddr)) { - nextaddr = 0; - sgsize = MIN(PAGE_SIZE, sgsize); - if ((curaddr & PAGE_MASK) + sgsize > PAGE_SIZE) - nextaddr = roundup2(curaddr, PAGE_SIZE); - curaddr = add_bounce_page(dmat, map, 0, curaddr, - nextaddr, sgsize); + sgsize = MIN(sgsize, PAGE_SIZE - (curaddr & PAGE_MASK)); + curaddr = add_bounce_page(dmat, map, 0, curaddr, 0, + sgsize); } sgsize = _bus_dmamap_addseg(dmat, map, curaddr, sgsize, segs, segp); @@ -743,7 +744,8 @@ bounce_bus_dmamap_load_buffer(bus_dma_tag_t dmat, bus_dmamap_t map, void *buf, if (((dmat->bounce_flags & BUS_DMA_COULD_BOUNCE) != 0) && map->pagesneeded != 0 && bus_dma_run_filter(&dmat->common, curaddr)) { - sgsize = MIN(PAGE_SIZE, max_sgsize); + sgsize = roundup2(sgsize, dmat->common.alignment); + sgsize = MIN(sgsize, max_sgsize); curaddr = add_bounce_page(dmat, map, kvaddr, curaddr, 0, sgsize); } else { @@ -772,6 +774,17 @@ bounce_bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map, int error, page_index; bus_size_t sgsize, max_sgsize; + if (dmat->common.flags & BUS_DMA_KEEP_PG_OFFSET) { + /* + * If we have to keep the offset of each page this function + * is not suitable, switch back to bus_dmamap_load_ma_triv + * which is going to do the right thing in this case. + */ + error = bus_dmamap_load_ma_triv(dmat, map, ma, buflen, ma_offs, + flags, segs, segp); + return (error); + } + if (map == NULL) map = &nobounce_dmamap; @@ -798,7 +811,10 @@ bounce_bus_dmamap_load_ma(bus_dma_tag_t dmat, bus_dmamap_t map, if (((dmat->bounce_flags & BUS_DMA_COULD_BOUNCE) != 0) && map->pagesneeded != 0 && bus_dma_run_filter(&dmat->common, paddr)) { - sgsize = MIN(PAGE_SIZE, max_sgsize); + sgsize = roundup2(sgsize, dmat->common.alignment); + sgsize = MIN(sgsize, max_sgsize); + KASSERT((sgsize & (dmat->common.alignment - 1)) == 0, + ("Segment size is not aligned")); /* * Check if two pages of the user provided buffer * are used. @@ -1159,6 +1175,13 @@ add_bounce_page(bus_dma_tag_t dmat, bus_dmamap_t map, vm_offset_t vaddr, bz->active_bpages++; mtx_unlock(&bounce_lock); + if (dmat->common.flags & BUS_DMA_KEEP_PG_OFFSET) { + /* Page offset needs to be preserved. */ + bpage->vaddr |= addr1 & PAGE_MASK; + bpage->busaddr |= addr1 & PAGE_MASK; + KASSERT(addr2 == 0, + ("Trying to bounce multiple pages with BUS_DMA_KEEP_PG_OFFSET")); + } bpage->datavaddr = vaddr; bpage->datapage[0] = PHYS_TO_VM_PAGE(addr1); KASSERT((addr2 & PAGE_MASK) == 0, ("Second page is not aligned")); @@ -1178,6 +1201,15 @@ free_bounce_page(bus_dma_tag_t dmat, struct bounce_page *bpage) bz = dmat->bounce_zone; bpage->datavaddr = 0; bpage->datacount = 0; + if (dmat->common.flags & BUS_DMA_KEEP_PG_OFFSET) { + /* + * Reset the bounce page to start at offset 0. Other uses + * of this bounce page may need to store a full page of + * data and/or assume it starts on a page boundary. + */ + bpage->vaddr &= ~PAGE_MASK; + bpage->busaddr &= ~PAGE_MASK; + } mtx_lock(&bounce_lock); STAILQ_INSERT_HEAD(&bz->bounce_page_list, bpage, links); From c1a43e73c56137b6cb0a5daf773c907d1bde966f Mon Sep 17 00:00:00 2001 From: Edward Tomasz Napierala Date: Fri, 15 Apr 2016 11:55:29 +0000 Subject: [PATCH 104/143] Sort variable declarations. MFC after: 1 month Sponsored by: The FreeBSD Foundation --- sys/kern/kern_racct.c | 13 ++++----- sys/kern/kern_rctl.c | 64 ++++++++++++++++++++----------------------- 2 files changed, 35 insertions(+), 42 deletions(-) diff --git a/sys/kern/kern_racct.c b/sys/kern/kern_racct.c index 438a249a323c..2b4d53ce26ac 100644 --- a/sys/kern/kern_racct.c +++ b/sys/kern/kern_racct.c @@ -472,8 +472,8 @@ racct_create(struct racct **racctp) static void racct_destroy_locked(struct racct **racctp) { - int i; struct racct *racct; + int i; ASSERT_RACCT_ENABLED(); @@ -668,8 +668,7 @@ racct_add_buf(struct proc *p, const struct buf *bp, int is_write) static int racct_set_locked(struct proc *p, int resource, uint64_t amount, int force) { - int64_t old_amount, decayed_amount; - int64_t diff_proc, diff_cred; + int64_t old_amount, decayed_amount, diff_proc, diff_cred; #ifdef RCTL int error; #endif @@ -964,10 +963,9 @@ racct_proc_fork_done(struct proc *child) void racct_proc_exit(struct proc *p) { - int i; - uint64_t runtime; struct timeval wallclock; - uint64_t pct_estimate, pct; + uint64_t pct_estimate, pct, runtime; + int i; if (!racct_enable) return; @@ -1206,8 +1204,7 @@ racctd(void) struct thread *td; struct proc *p; struct timeval wallclock; - uint64_t runtime; - uint64_t pct, pct_estimate; + uint64_t pct, pct_estimate, runtime; ASSERT_RACCT_ENABLED(); diff --git a/sys/kern/kern_rctl.c b/sys/kern/kern_rctl.c index 98b5055500c9..6dba8b539a4e 100644 --- a/sys/kern/kern_rctl.c +++ b/sys/kern/kern_rctl.c @@ -210,8 +210,8 @@ static struct dict actionnames[] = { static void rctl_init(void); SYSINIT(rctl, SI_SUB_RACCT, SI_ORDER_FIRST, rctl_init, NULL); -static uma_zone_t rctl_rule_link_zone; static uma_zone_t rctl_rule_zone; +static uma_zone_t rctl_rule_link_zone; static struct rwlock rctl_lock; RW_SYSINIT(rctl_lock, &rctl_lock, "RCTL lock"); @@ -229,8 +229,7 @@ static MALLOC_DEFINE(M_RCTL, "rctl", "Resource Limits"); static int rctl_throttle_min_sysctl(SYSCTL_HANDLER_ARGS) { - int val = rctl_throttle_min; - int error; + int error, val = rctl_throttle_min; error = sysctl_handle_int(oidp, &val, 0, req); if (error || !req->newptr) @@ -247,8 +246,7 @@ static int rctl_throttle_min_sysctl(SYSCTL_HANDLER_ARGS) static int rctl_throttle_max_sysctl(SYSCTL_HANDLER_ARGS) { - int val = rctl_throttle_max; - int error; + int error, val = rctl_throttle_max; error = sysctl_handle_int(oidp, &val, 0, req); if (error || !req->newptr) @@ -265,8 +263,7 @@ static int rctl_throttle_max_sysctl(SYSCTL_HANDLER_ARGS) static int rctl_throttle_pct_sysctl(SYSCTL_HANDLER_ARGS) { - int val = rctl_throttle_pct; - int error; + int error, val = rctl_throttle_pct; error = sysctl_handle_int(oidp, &val, 0, req); if (error || !req->newptr) @@ -283,8 +280,7 @@ static int rctl_throttle_pct_sysctl(SYSCTL_HANDLER_ARGS) static int rctl_throttle_pct2_sysctl(SYSCTL_HANDLER_ARGS) { - int val = rctl_throttle_pct2; - int error; + int error, val = rctl_throttle_pct2; error = sysctl_handle_int(oidp, &val, 0, req); if (error || !req->newptr) @@ -367,8 +363,8 @@ rctl_proc_rule_to_racct(const struct proc *p, const struct rctl_rule *rule) static int64_t rctl_available_resource(const struct proc *p, const struct rctl_rule *rule) { - int64_t available; const struct racct *racct; + int64_t available; ASSERT_RACCT_ENABLED(); RCTL_LOCK_ASSERT(); @@ -515,10 +511,10 @@ rctl_enforce(struct proc *p, int resource, uint64_t amount) struct rctl_rule *rule; struct rctl_rule_link *link; struct sbuf sb; + char *buf; int64_t available; uint64_t sleep_ms, sleep_ratio; int should_deny = 0; - char *buf; ASSERT_RACCT_ENABLED(); @@ -945,8 +941,8 @@ static int rctl_racct_remove_rules(struct racct *racct, const struct rctl_rule *filter) { - int removed = 0; struct rctl_rule_link *link, *linktmp; + int removed = 0; ASSERT_RACCT_ENABLED(); RCTL_WLOCK_ASSERT(); @@ -1160,11 +1156,11 @@ rctl_rule_fully_specified(const struct rctl_rule *rule) static int rctl_string_to_rule(char *rulestr, struct rctl_rule **rulep) { - int error = 0; + struct rctl_rule *rule; char *subjectstr, *subject_idstr, *resourcestr, *actionstr, *amountstr, *perstr; - struct rctl_rule *rule; id_t id; + int error = 0; ASSERT_RACCT_ENABLED(); @@ -1450,8 +1446,8 @@ rctl_rule_remove_callback(struct racct *racct, void *arg2, void *arg3) int rctl_rule_remove(struct rctl_rule *filter) { - int found = 0; struct proc *p; + int found = 0; ASSERT_RACCT_ENABLED(); @@ -1554,8 +1550,8 @@ rctl_rule_to_sbuf(struct sbuf *sb, const struct rctl_rule *rule) static int rctl_read_inbuf(char **inputstr, const char *inbufp, size_t inbuflen) { - int error; char *str; + int error; ASSERT_RACCT_ENABLED(); @@ -1603,9 +1599,9 @@ rctl_write_outbuf(struct sbuf *outputsbuf, char *outbufp, size_t outbuflen) static struct sbuf * rctl_racct_to_sbuf(struct racct *racct, int sloppy) { - int i; - int64_t amount; struct sbuf *sb; + int64_t amount; + int i; ASSERT_RACCT_ENABLED(); @@ -1625,14 +1621,14 @@ rctl_racct_to_sbuf(struct racct *racct, int sloppy) int sys_rctl_get_racct(struct thread *td, struct rctl_get_racct_args *uap) { - int error; - char *inputstr; struct rctl_rule *filter; struct sbuf *outputsbuf = NULL; struct proc *p; struct uidinfo *uip; struct loginclass *lc; struct prison_racct *prr; + char *inputstr; + int error; if (!racct_enable) return (ENOSYS); @@ -1721,13 +1717,13 @@ rctl_get_rules_callback(struct racct *racct, void *arg2, void *arg3) int sys_rctl_get_rules(struct thread *td, struct rctl_get_rules_args *uap) { - int error; - size_t bufsize; - char *inputstr, *buf; struct sbuf *sb; struct rctl_rule *filter; struct rctl_rule_link *link; struct proc *p; + char *inputstr, *buf; + size_t bufsize; + int error; if (!racct_enable) return (ENOSYS); @@ -1807,12 +1803,12 @@ sys_rctl_get_rules(struct thread *td, struct rctl_get_rules_args *uap) int sys_rctl_get_limits(struct thread *td, struct rctl_get_limits_args *uap) { - int error; - size_t bufsize; - char *inputstr, *buf; struct sbuf *sb; struct rctl_rule *filter; struct rctl_rule_link *link; + char *inputstr, *buf; + size_t bufsize; + int error; if (!racct_enable) return (ENOSYS); @@ -1889,9 +1885,9 @@ sys_rctl_get_limits(struct thread *td, struct rctl_get_limits_args *uap) int sys_rctl_add_rule(struct thread *td, struct rctl_add_rule_args *uap) { - int error; struct rctl_rule *rule; char *inputstr; + int error; if (!racct_enable) return (ENOSYS); @@ -1934,9 +1930,9 @@ sys_rctl_add_rule(struct thread *td, struct rctl_add_rule_args *uap) int sys_rctl_remove_rule(struct thread *td, struct rctl_remove_rule_args *uap) { - int error; struct rctl_rule *filter; char *inputstr; + int error; if (!racct_enable) return (ENOSYS); @@ -1970,12 +1966,12 @@ sys_rctl_remove_rule(struct thread *td, struct rctl_remove_rule_args *uap) void rctl_proc_ucred_changed(struct proc *p, struct ucred *newcred) { - int rulecnt, i; + LIST_HEAD(, rctl_rule_link) newrules; struct rctl_rule_link *link, *newlink; struct uidinfo *newuip; struct loginclass *newlc; struct prison_racct *newprr; - LIST_HEAD(, rctl_rule_link) newrules; + int rulecnt, i; ASSERT_RACCT_ENABLED(); @@ -2118,9 +2114,9 @@ rctl_proc_ucred_changed(struct proc *p, struct ucred *newcred) int rctl_proc_fork(struct proc *parent, struct proc *child) { - int error; - struct rctl_rule_link *link; struct rctl_rule *rule; + struct rctl_rule_link *link; + int error; LIST_INIT(&child->p_racct->r_rule_links); @@ -2197,11 +2193,11 @@ rctl_init(void) if (!racct_enable) return; + rctl_rule_zone = uma_zcreate("rctl_rule", sizeof(struct rctl_rule), + NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); rctl_rule_link_zone = uma_zcreate("rctl_rule_link", sizeof(struct rctl_rule_link), NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); - rctl_rule_zone = uma_zcreate("rctl_rule", sizeof(struct rctl_rule), - NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); /* * Set default values, making sure not to overwrite the ones From d4a2eaef398754978176419006caca34f6f2e440 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 12:16:15 +0000 Subject: [PATCH 105/143] ofed: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. Reviewed by: hselasky --- sys/ofed/drivers/infiniband/hw/mlx4/main.c | 2 +- sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_main.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sys/ofed/drivers/infiniband/hw/mlx4/main.c b/sys/ofed/drivers/infiniband/hw/mlx4/main.c index 1f14e5cf887b..5be92a221286 100644 --- a/sys/ofed/drivers/infiniband/hw/mlx4/main.c +++ b/sys/ofed/drivers/infiniband/hw/mlx4/main.c @@ -1297,7 +1297,7 @@ static int del_gid_entry(struct ib_qp *ibqp, union ib_gid *gid) pr_warn("could not find mgid entry\n"); mutex_unlock(&mqp->mutex); - return ge != 0 ? 0 : -EINVAL; + return ge != NULL ? 0 : -EINVAL; } static int _mlx4_ib_mcg_detach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid, diff --git a/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_main.c b/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_main.c index 9a68b232ba89..5bef672735b8 100644 --- a/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_main.c +++ b/sys/ofed/drivers/infiniband/ulp/ipoib/ipoib_main.c @@ -1485,7 +1485,7 @@ ipoib_resolvemulti(struct ifnet *ifp, struct sockaddr **llsa, e_addr = LLADDR(sdl); if (!IPOIB_IS_MULTICAST(e_addr)) return EADDRNOTAVAIL; - *llsa = 0; + *llsa = NULL; return 0; #ifdef INET From 8806325ade5e2696c4a1a374aa7852f59bad80ad Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 12:17:34 +0000 Subject: [PATCH 106/143] sparc64: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/sparc64/ebus/ebus.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/sparc64/ebus/ebus.c b/sys/sparc64/ebus/ebus.c index 49abe18002d5..55a90a3cd5d5 100644 --- a/sys/sparc64/ebus/ebus.c +++ b/sys/sparc64/ebus/ebus.c @@ -370,7 +370,7 @@ ebus_pci_attach(device_t dev) eri = &sc->sc_rinfo[i]; if (i < rnum) rman_fini(&eri->eri_rman); - if (eri->eri_res != 0) { + if (eri->eri_res != NULL) { bus_release_resource(dev, eri->eri_rtype, PCIR_BAR(rnum), eri->eri_res); } From 7a6ab8f19e65bfb15f46c4ae93c86da6502b58fa Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 12:24:01 +0000 Subject: [PATCH 107/143] netpfil: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. Reviewed by: ae --- sys/netpfil/ipfw/ip_fw_iface.c | 2 +- sys/netpfil/ipfw/ip_fw_sockopt.c | 2 +- sys/netpfil/ipfw/ip_fw_table.c | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sys/netpfil/ipfw/ip_fw_iface.c b/sys/netpfil/ipfw/ip_fw_iface.c index b7c450c6dc46..07d24de28a3b 100644 --- a/sys/netpfil/ipfw/ip_fw_iface.c +++ b/sys/netpfil/ipfw/ip_fw_iface.c @@ -471,7 +471,7 @@ export_iface_internal(struct namedobj_instance *ii, struct named_object *no, da = (struct dump_iface_args *)arg; i = (ipfw_iface_info *)ipfw_get_sopt_space(da->sd, sizeof(*i)); - KASSERT(i != 0, ("previously checked buffer is not enough")); + KASSERT(i != NULL, ("previously checked buffer is not enough")); iif = (struct ipfw_iface *)no; diff --git a/sys/netpfil/ipfw/ip_fw_sockopt.c b/sys/netpfil/ipfw/ip_fw_sockopt.c index 00d1a0aaf1af..c63a3036fc5f 100644 --- a/sys/netpfil/ipfw/ip_fw_sockopt.c +++ b/sys/netpfil/ipfw/ip_fw_sockopt.c @@ -2797,7 +2797,7 @@ dump_soptcodes(struct ip_fw_chain *chain, ip_fw3_opheader *op3, for (n = 1; n <= count; n++) { i = (ipfw_sopt_info *)ipfw_get_sopt_space(sd, sizeof(*i)); - KASSERT(i != 0, ("previously checked buffer is not enough")); + KASSERT(i != NULL, ("previously checked buffer is not enough")); sh = &ctl3_handlers[n]; i->opcode = sh->opcode; i->version = sh->version; diff --git a/sys/netpfil/ipfw/ip_fw_table.c b/sys/netpfil/ipfw/ip_fw_table.c index 4af7c88e29d2..175202a08cb2 100644 --- a/sys/netpfil/ipfw/ip_fw_table.c +++ b/sys/netpfil/ipfw/ip_fw_table.c @@ -2130,7 +2130,7 @@ export_table_internal(struct namedobj_instance *ni, struct named_object *no, dta = (struct dump_table_args *)arg; i = (ipfw_xtable_info *)ipfw_get_sopt_space(dta->sd, sizeof(*i)); - KASSERT(i != 0, ("previously checked buffer is not enough")); + KASSERT(i != NULL, ("previously checked buffer is not enough")); export_table_info(dta->ch, (struct table_config *)no, i); } @@ -2746,7 +2746,7 @@ list_table_algo(struct ip_fw_chain *ch, ip_fw3_opheader *op3, for (n = 1; n <= count; n++) { i = (ipfw_ta_info *)ipfw_get_sopt_space(sd, sizeof(*i)); - KASSERT(i != 0, ("previously checked buffer is not enough")); + KASSERT(i != NULL, ("previously checked buffer is not enough")); ta = tcfg->algo[n]; strlcpy(i->algoname, ta->name, sizeof(i->algoname)); i->type = ta->type; From dfaa65fc8dd71e7e4626ba1d581108fe328d09b4 Mon Sep 17 00:00:00 2001 From: Konstantin Belousov Date: Fri, 15 Apr 2016 12:55:40 +0000 Subject: [PATCH 108/143] Sync cam.ko module source list with the static kernel file list. Sponsored by: The FreeBSD Foundation --- sys/modules/cam/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/modules/cam/Makefile b/sys/modules/cam/Makefile index 19bd9ec82f61..603f0555882c 100644 --- a/sys/modules/cam/Makefile +++ b/sys/modules/cam/Makefile @@ -21,7 +21,7 @@ SRCS+= cam_compat.c .if exists($S/${MACHINE}/${MACHINE}/cam_machdep.c) SRCS+= cam_machdep.c .endif -SRCS+= cam_periph.c cam_queue.c cam_sim.c cam_xpt.c +SRCS+= cam_iosched.c cam_periph.c cam_queue.c cam_sim.c cam_xpt.c SRCS+= scsi_all.c scsi_cd.c scsi_ch.c SRCS+= scsi_da.c SRCS+= scsi_pass.c From 23e6fff29d709f4dfeddb88443f1b6db15e1b990 Mon Sep 17 00:00:00 2001 From: Edward Tomasz Napierala Date: Fri, 15 Apr 2016 13:34:59 +0000 Subject: [PATCH 109/143] Allocate RACCT/RCTL zones without UMA_ZONE_NOFREE; no idea why it was there in the first place. MFC after: 1 month Sponsored by: The FreeBSD Foundation --- sys/kern/kern_racct.c | 2 +- sys/kern/kern_rctl.c | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sys/kern/kern_racct.c b/sys/kern/kern_racct.c index 2b4d53ce26ac..d6f75101f0dc 100644 --- a/sys/kern/kern_racct.c +++ b/sys/kern/kern_racct.c @@ -1314,7 +1314,7 @@ racct_init(void) return; racct_zone = uma_zcreate("racct", sizeof(struct racct), - NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); + NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); /* * XXX: Move this somewhere. */ diff --git a/sys/kern/kern_rctl.c b/sys/kern/kern_rctl.c index 6dba8b539a4e..9647090662d6 100644 --- a/sys/kern/kern_rctl.c +++ b/sys/kern/kern_rctl.c @@ -2194,10 +2194,10 @@ rctl_init(void) return; rctl_rule_zone = uma_zcreate("rctl_rule", sizeof(struct rctl_rule), - NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); + NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); rctl_rule_link_zone = uma_zcreate("rctl_rule_link", sizeof(struct rctl_rule_link), NULL, NULL, NULL, NULL, - UMA_ALIGN_PTR, UMA_ZONE_NOFREE); + UMA_ALIGN_PTR, 0); /* * Set default values, making sure not to overwrite the ones From e2d4ce8aeff983ddb3479a339105799c07d1fcfc Mon Sep 17 00:00:00 2001 From: Andrew Turner Date: Fri, 15 Apr 2016 14:19:25 +0000 Subject: [PATCH 110/143] Add initial GICv2m support to the arm GIC driver. This will be used to support MSI and MSI-X interrupts, however intrng needs updates before this can happen. For now we just attach the driver until the MSI API is ready. Obtained from: ABT Systems Ltd Sponsored by: The FreeBSD Foundation Differential Revision: https://reviews.freebsd.org/D5950 --- sys/arm/arm/gic.c | 300 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 300 insertions(+) diff --git a/sys/arm/arm/gic.c b/sys/arm/arm/gic.c index 5c0aece1987f..ced66d5d32c7 100644 --- a/sys/arm/arm/gic.c +++ b/sys/arm/arm/gic.c @@ -134,6 +134,19 @@ u_int sgi_first_unused = GIC_FIRST_SGI; #endif #endif +#ifdef ARM_INTRNG +struct arm_gic_range { + uint64_t bus; + uint64_t host; + uint64_t size; +}; + +struct arm_gic_devinfo { + struct ofw_bus_devinfo obdinfo; + struct resource_list rl; +}; +#endif + struct arm_gic_softc { device_t gic_dev; #ifdef ARM_INTRNG @@ -151,6 +164,14 @@ struct arm_gic_softc { #ifdef GIC_DEBUG_SPURIOUS uint32_t last_irq[MAXCPU]; #endif + +#ifdef ARM_INTRNG + /* FDT child data */ + pcell_t addr_cells; + pcell_t size_cells; + int nranges; + struct arm_gic_range * ranges; +#endif }; #ifdef ARM_INTRNG @@ -195,6 +216,7 @@ static struct ofw_compat_data compat_data[] = { {"arm,cortex-a7-gic", true}, {"arm,arm11mp-gic", true}, {"brcm,brahma-b15-gic", true}, + {"qcom,msm-qgic2", true}, {NULL, false} }; @@ -437,6 +459,107 @@ arm_gic_register_isrcs(struct arm_gic_softc *sc, uint32_t num) sc->nirqs = num; return (0); } + +static int +arm_gic_fill_ranges(phandle_t node, struct arm_gic_softc *sc) +{ + pcell_t host_cells; + cell_t *base_ranges; + ssize_t nbase_ranges; + int i, j, k; + + host_cells = 1; + OF_getencprop(OF_parent(node), "#address-cells", &host_cells, + sizeof(host_cells)); + sc->addr_cells = 2; + OF_getencprop(node, "#address-cells", &sc->addr_cells, + sizeof(sc->addr_cells)); + sc->size_cells = 2; + OF_getencprop(node, "#size-cells", &sc->size_cells, + sizeof(sc->size_cells)); + + nbase_ranges = OF_getproplen(node, "ranges"); + if (nbase_ranges < 0) + return (-1); + sc->nranges = nbase_ranges / sizeof(cell_t) / + (sc->addr_cells + host_cells + sc->size_cells); + if (sc->nranges == 0) + return (0); + + sc->ranges = malloc(sc->nranges * sizeof(sc->ranges[0]), + M_DEVBUF, M_WAITOK); + base_ranges = malloc(nbase_ranges, M_DEVBUF, M_WAITOK); + OF_getencprop(node, "ranges", base_ranges, nbase_ranges); + + for (i = 0, j = 0; i < sc->nranges; i++) { + sc->ranges[i].bus = 0; + for (k = 0; k < sc->addr_cells; k++) { + sc->ranges[i].bus <<= 32; + sc->ranges[i].bus |= base_ranges[j++]; + } + sc->ranges[i].host = 0; + for (k = 0; k < host_cells; k++) { + sc->ranges[i].host <<= 32; + sc->ranges[i].host |= base_ranges[j++]; + } + sc->ranges[i].size = 0; + for (k = 0; k < sc->size_cells; k++) { + sc->ranges[i].size <<= 32; + sc->ranges[i].size |= base_ranges[j++]; + } + } + + free(base_ranges, M_DEVBUF); + return (sc->nranges); +} + +static bool +arm_gic_add_children(device_t dev) +{ + struct arm_gic_softc *sc; + struct arm_gic_devinfo *dinfo; + phandle_t child, node; + device_t cdev; + + sc = device_get_softc(dev); + node = ofw_bus_get_node(dev); + + /* If we have no children don't probe for them */ + child = OF_child(node); + if (child == 0) + return (false); + + if (arm_gic_fill_ranges(node, sc) < 0) { + device_printf(dev, "Have a child, but no ranges\n"); + return (false); + } + + for (; child != 0; child = OF_peer(child)) { + dinfo = malloc(sizeof(*dinfo), M_DEVBUF, M_WAITOK | M_ZERO); + + if (ofw_bus_gen_setup_devinfo(&dinfo->obdinfo, child) != 0) { + free(dinfo, M_DEVBUF); + continue; + } + + resource_list_init(&dinfo->rl); + ofw_bus_reg_to_rl(dev, child, sc->addr_cells, + sc->size_cells, &dinfo->rl); + + cdev = device_add_child(dev, NULL, -1); + if (cdev == NULL) { + device_printf(dev, "<%s>: device_add_child failed\n", + dinfo->obdinfo.obd_name); + resource_list_free(&dinfo->rl); + ofw_bus_gen_destroy_devinfo(&dinfo->obdinfo); + free(dinfo, M_DEVBUF); + continue; + } + device_set_ivars(cdev, dinfo); + } + + return (true); +} #endif static int @@ -578,6 +701,13 @@ arm_gic_attach(device_t dev) } OF_device_register_xref(xref, dev); + + /* If we have children probe and attach them */ + if (arm_gic_add_children(dev)) { + bus_generic_probe(dev); + return (bus_generic_attach(dev)); + } + return (0); cleanup: @@ -592,6 +722,75 @@ arm_gic_attach(device_t dev) } #ifdef ARM_INTRNG +static struct resource * +arm_gic_alloc_resource(device_t bus, device_t child, int type, int *rid, + rman_res_t start, rman_res_t end, rman_res_t count, u_int flags) +{ + struct arm_gic_softc *sc; + struct arm_gic_devinfo *di; + struct resource_list_entry *rle; + int j; + + KASSERT(type == SYS_RES_MEMORY, ("Invalid resoure type %x", type)); + + sc = device_get_softc(bus); + + /* + * Request for the default allocation with a given rid: use resource + * list stored in the local device info. + */ + if (RMAN_IS_DEFAULT_RANGE(start, end)) { + if ((di = device_get_ivars(child)) == NULL) + return (NULL); + + if (type == SYS_RES_IOPORT) + type = SYS_RES_MEMORY; + + rle = resource_list_find(&di->rl, type, *rid); + if (rle == NULL) { + if (bootverbose) + device_printf(bus, "no default resources for " + "rid = %d, type = %d\n", *rid, type); + return (NULL); + } + start = rle->start; + end = rle->end; + count = rle->count; + } + + /* Remap through ranges property */ + for (j = 0; j < sc->nranges; j++) { + if (start >= sc->ranges[j].bus && end < + sc->ranges[j].bus + sc->ranges[j].size) { + start -= sc->ranges[j].bus; + start += sc->ranges[j].host; + end -= sc->ranges[j].bus; + end += sc->ranges[j].host; + break; + } + } + if (j == sc->nranges && sc->nranges != 0) { + if (bootverbose) + device_printf(bus, "Could not map resource " + "%#jx-%#jx\n", (uintmax_t)start, (uintmax_t)end); + + return (NULL); + } + + return (bus_generic_alloc_resource(bus, child, type, rid, start, end, + count, flags)); +} + +static const struct ofw_bus_devinfo * +arm_gic_ofw_get_devinfo(device_t bus __unused, device_t child) +{ + struct arm_gic_devinfo *di; + + di = device_get_ivars(child); + + return (&di->obdinfo); +} + static int arm_gic_intr(void *arg) { @@ -1231,7 +1430,22 @@ static device_method_t arm_gic_methods[] = { /* Device interface */ DEVMETHOD(device_probe, arm_gic_probe), DEVMETHOD(device_attach, arm_gic_attach), + #ifdef ARM_INTRNG + /* Bus interface */ + DEVMETHOD(bus_add_child, bus_generic_add_child), + DEVMETHOD(bus_alloc_resource, arm_gic_alloc_resource), + DEVMETHOD(bus_release_resource, bus_generic_release_resource), + DEVMETHOD(bus_activate_resource,bus_generic_activate_resource), + + /* ofw_bus interface */ + DEVMETHOD(ofw_bus_get_devinfo, arm_gic_ofw_get_devinfo), + DEVMETHOD(ofw_bus_get_compat, ofw_bus_gen_get_compat), + DEVMETHOD(ofw_bus_get_model, ofw_bus_gen_get_model), + DEVMETHOD(ofw_bus_get_name, ofw_bus_gen_get_name), + DEVMETHOD(ofw_bus_get_node, ofw_bus_gen_get_node), + DEVMETHOD(ofw_bus_get_type, ofw_bus_gen_get_type), + /* Interrupt controller interface */ DEVMETHOD(pic_disable_intr, arm_gic_disable_intr), DEVMETHOD(pic_enable_intr, arm_gic_enable_intr), @@ -1263,3 +1477,89 @@ EARLY_DRIVER_MODULE(gic, simplebus, arm_gic_driver, arm_gic_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE); EARLY_DRIVER_MODULE(gic, ofwbus, arm_gic_driver, arm_gic_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE); + +#ifdef ARM_INTRNG +/* + * GICv2m support -- the GICv2 MSI/MSI-X controller. + */ + +#define GICV2M_MSI_TYPER 0x008 +#define MSI_TYPER_SPI_BASE(x) (((x) >> 16) & 0x3ff) +#define MSI_TYPER_SPI_COUNT(x) (((x) >> 0) & 0x3ff) +#define GICv2M_MSI_SETSPI_NS 0x040 +#define GICV2M_MSI_IIDR 0xFCC + +struct arm_gicv2m_softc { + struct resource *sc_mem; + struct mtx sc_mutex; + u_int sc_spi_start; + u_int sc_spi_count; + u_int sc_spi_offset; +}; + +static struct ofw_compat_data gicv2m_compat_data[] = { + {"arm,gic-v2m-frame", true}, + {NULL, false} +}; + +static int +arm_gicv2m_probe(device_t dev) +{ + + if (!ofw_bus_status_okay(dev)) + return (ENXIO); + + if (!ofw_bus_search_compatible(dev, gicv2m_compat_data)->ocd_data) + return (ENXIO); + + device_set_desc(dev, "ARM Generic Interrupt Controller MSI/MSIX"); + return (BUS_PROBE_DEFAULT); +} + +static int +arm_gicv2m_attach(device_t dev) +{ + struct arm_gicv2m_softc *sc; + uint32_t typer; + int rid; + + sc = device_get_softc(dev); + + rid = 0; + sc->sc_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid, + RF_ACTIVE); + if (sc->sc_mem == NULL) { + device_printf(dev, "Unable to allocate resources\n"); + return (ENXIO); + } + + typer = bus_read_4(sc->sc_mem, GICV2M_MSI_TYPER); + sc->sc_spi_start = MSI_TYPER_SPI_BASE(typer); + sc->sc_spi_count = MSI_TYPER_SPI_COUNT(typer); + + mtx_init(&sc->sc_mutex, "GICv2m lock", "", MTX_DEF); + + if (bootverbose) + device_printf(dev, "using spi %u to %u\n", sc->sc_spi_start, + sc->sc_spi_start + sc->sc_spi_count - 1); + + return (0); +} + +static device_method_t arm_gicv2m_methods[] = { + /* Device interface */ + DEVMETHOD(device_probe, arm_gicv2m_probe), + DEVMETHOD(device_attach, arm_gicv2m_attach), + + /* End */ + DEVMETHOD_END +}; + +DEFINE_CLASS_0(gicv2m, arm_gicv2m_driver, arm_gicv2m_methods, + sizeof(struct arm_gicv2m_softc)); + +static devclass_t arm_gicv2m_devclass; + +EARLY_DRIVER_MODULE(gicv2m, gic, arm_gicv2m_driver, + arm_gicv2m_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE); +#endif From 26f0e234f71dc88e394bbe1421c2508f7178aec1 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 14:25:13 +0000 Subject: [PATCH 111/143] powerpc: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. Reviewed by: jhibbits --- sys/powerpc/powerpc/db_disasm.c | 4 ++-- sys/powerpc/powerpc/elf32_machdep.c | 2 +- sys/powerpc/powerpc/elf64_machdep.c | 2 +- sys/powerpc/psim/iobus.c | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/sys/powerpc/powerpc/db_disasm.c b/sys/powerpc/powerpc/db_disasm.c index 6d525b37080f..71c35c5fcd41 100644 --- a/sys/powerpc/powerpc/db_disasm.c +++ b/sys/powerpc/powerpc/db_disasm.c @@ -836,9 +836,9 @@ disasm_fields(const struct opcode *popcode, instr_t instr, vm_offset_t loc, reg = "tbu"; break; default: - reg = 0; + reg = NULL; } - if (reg == 0) + if (reg == NULL) pstr += sprintf(pstr, ", [unknown tbr %d ]", tbr); else pstr += sprintf(pstr, ", %s", reg); diff --git a/sys/powerpc/powerpc/elf32_machdep.c b/sys/powerpc/powerpc/elf32_machdep.c index eed76c908aef..9954a330f22a 100644 --- a/sys/powerpc/powerpc/elf32_machdep.c +++ b/sys/powerpc/powerpc/elf32_machdep.c @@ -257,7 +257,7 @@ elf_reloc_internal(linker_file_t lf, Elf_Addr relocbase, const void *data, void elf_reloc_self(Elf_Dyn *dynp, Elf_Addr relocbase) { - Elf_Rela *rela = 0, *relalim; + Elf_Rela *rela = NULL, *relalim; Elf_Addr relasz = 0; Elf_Addr *where; diff --git a/sys/powerpc/powerpc/elf64_machdep.c b/sys/powerpc/powerpc/elf64_machdep.c index 032728c67b6d..084200efae5c 100644 --- a/sys/powerpc/powerpc/elf64_machdep.c +++ b/sys/powerpc/powerpc/elf64_machdep.c @@ -312,7 +312,7 @@ elf_reloc_internal(linker_file_t lf, Elf_Addr relocbase, const void *data, void elf_reloc_self(Elf_Dyn *dynp, Elf_Addr relocbase) { - Elf_Rela *rela = 0, *relalim; + Elf_Rela *rela = NULL, *relalim; Elf_Addr relasz = 0; Elf_Addr *where; diff --git a/sys/powerpc/psim/iobus.c b/sys/powerpc/psim/iobus.c index ce4a93a094f0..37a23d18e772 100644 --- a/sys/powerpc/psim/iobus.c +++ b/sys/powerpc/psim/iobus.c @@ -272,7 +272,7 @@ iobus_read_ivar(device_t dev, device_t child, int which, uintptr_t *result) { struct iobus_devinfo *dinfo; - if ((dinfo = device_get_ivars(child)) == 0) + if ((dinfo = device_get_ivars(child)) == NULL) return (ENOENT); switch (which) { From 7b6cea2b0117cf9f68a76b7bce7e9369684d92ba Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 14:26:24 +0000 Subject: [PATCH 112/143] mips: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. Reviewed by: adrian --- sys/mips/adm5120/obio.c | 2 +- sys/mips/alchemy/obio.c | 2 +- sys/mips/atheros/apb.c | 2 +- sys/mips/idt/obio.c | 2 +- sys/mips/mips/machdep.c | 2 +- sys/mips/mips/nexus.c | 2 +- sys/mips/nlm/xlp_simplebus.c | 2 +- sys/mips/rmi/xlr_pci.c | 2 +- sys/mips/rt305x/obio.c | 2 +- sys/mips/rt305x/rt305x_gpio.c | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/sys/mips/adm5120/obio.c b/sys/mips/adm5120/obio.c index 8b62629c977a..0e09886f7e3a 100644 --- a/sys/mips/adm5120/obio.c +++ b/sys/mips/adm5120/obio.c @@ -270,7 +270,7 @@ obio_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) { + if (rv == NULL) { printf("%s: could not reserve resource\n", __func__); return (0); } diff --git a/sys/mips/alchemy/obio.c b/sys/mips/alchemy/obio.c index 96b1f1d75b39..b85ca48dd9ff 100644 --- a/sys/mips/alchemy/obio.c +++ b/sys/mips/alchemy/obio.c @@ -271,7 +271,7 @@ obio_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) { + if (rv == NULL) { printf("%s: could not reserve resource\n", __func__); return (0); } diff --git a/sys/mips/atheros/apb.c b/sys/mips/atheros/apb.c index abae9c27b64f..6a38c7dc7158 100644 --- a/sys/mips/atheros/apb.c +++ b/sys/mips/atheros/apb.c @@ -223,7 +223,7 @@ apb_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) { + if (rv == NULL) { printf("%s: could not reserve resource\n", __func__); return (0); } diff --git a/sys/mips/idt/obio.c b/sys/mips/idt/obio.c index b95b11ac66cf..f151a79eb28f 100644 --- a/sys/mips/idt/obio.c +++ b/sys/mips/idt/obio.c @@ -204,7 +204,7 @@ obio_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) { + if (rv == NULL) { printf("%s: could not reserve resource\n", __func__); return (0); } diff --git a/sys/mips/mips/machdep.c b/sys/mips/mips/machdep.c index 5d25d881fb6c..3d44cdad0e5f 100644 --- a/sys/mips/mips/machdep.c +++ b/sys/mips/mips/machdep.c @@ -316,7 +316,7 @@ cpu_initclocks(void) cpu_initclocks_bsp(); } -struct msgbuf *msgbufp=0; +struct msgbuf *msgbufp = NULL; /* * Initialize the hardware exception vectors, and the jump table used to diff --git a/sys/mips/mips/nexus.c b/sys/mips/mips/nexus.c index a2a8e52715b8..908d5bca0dad 100644 --- a/sys/mips/mips/nexus.c +++ b/sys/mips/mips/nexus.c @@ -315,7 +315,7 @@ nexus_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) { + if (rv == NULL) { printf("%s: could not reserve resource for %s\n", __func__, device_get_nameunit(child)); return (0); diff --git a/sys/mips/nlm/xlp_simplebus.c b/sys/mips/nlm/xlp_simplebus.c index 413775b456d6..eb42a864a54e 100644 --- a/sys/mips/nlm/xlp_simplebus.c +++ b/sys/mips/nlm/xlp_simplebus.c @@ -244,7 +244,7 @@ xlp_simplebus_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) { + if (rv == NULL) { device_printf(bus, "%s: could not reserve resource for %s\n", __func__, device_get_nameunit(child)); return (NULL); diff --git a/sys/mips/rmi/xlr_pci.c b/sys/mips/rmi/xlr_pci.c index 53581a6fed8d..3d985039d559 100644 --- a/sys/mips/rmi/xlr_pci.c +++ b/sys/mips/rmi/xlr_pci.c @@ -537,7 +537,7 @@ xlr_pci_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) + if (rv == NULL) return (0); rman_set_rid(rv, *rid); diff --git a/sys/mips/rt305x/obio.c b/sys/mips/rt305x/obio.c index ac2723060fac..fc8a4ac34177 100644 --- a/sys/mips/rt305x/obio.c +++ b/sys/mips/rt305x/obio.c @@ -326,7 +326,7 @@ obio_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) { + if (rv == NULL) { printf("%s: could not reserve resource\n", __func__); return (0); } diff --git a/sys/mips/rt305x/rt305x_gpio.c b/sys/mips/rt305x/rt305x_gpio.c index e4f645f9b1c6..56b734aa11f3 100644 --- a/sys/mips/rt305x/rt305x_gpio.c +++ b/sys/mips/rt305x/rt305x_gpio.c @@ -562,7 +562,7 @@ rt305x_gpio_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) { + if (rv == NULL) { printf("%s: could not reserve resource\n", __func__); return (0); } From 2049b03cc84a7012f6f7d049322c083242bf22d2 Mon Sep 17 00:00:00 2001 From: Andrew Turner Date: Fri, 15 Apr 2016 14:28:34 +0000 Subject: [PATCH 113/143] Add a flag field to struct gic_irqsrc and use it to mark when we should write to the End of Interrupt (EOI) register before handling the interrupt. This should be a noop as it will be set for all edge triggered interrupts, however this will not be the case for MSI interrupts. These are also edge triggered, however we should not write to the EOI register until later in arm_gic_pre_ithread. Obtained from: ABT Systems Ltd Sponsored by: The FreeBSD Foundation --- sys/arm/arm/gic.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sys/arm/arm/gic.c b/sys/arm/arm/gic.c index ced66d5d32c7..0d201fdf45ef 100644 --- a/sys/arm/arm/gic.c +++ b/sys/arm/arm/gic.c @@ -122,6 +122,8 @@ struct gic_irqsrc { uint32_t gi_irq; enum intr_polarity gi_pol; enum intr_trigger gi_trig; +#define GI_FLAG_EARLY_EOI (1 << 0) + u_int gi_flags; }; static u_int gic_irq_cpu; @@ -853,12 +855,12 @@ arm_gic_intr(void *arg) #ifdef GIC_DEBUG_SPURIOUS sc->last_irq[PCPU_GET(cpuid)] = irq; #endif - if (gi->gi_trig == INTR_TRIGGER_EDGE) + if ((gi->gi_flags & GI_FLAG_EARLY_EOI) == GI_FLAG_EARLY_EOI) gic_c_write_4(sc, GICC_EOIR, irq_active_reg); if (intr_isrc_dispatch(&gi->gi_isrc, tf) != 0) { gic_irq_mask(sc, irq); - if (gi->gi_trig != INTR_TRIGGER_EDGE) + if ((gi->gi_flags & GI_FLAG_EARLY_EOI) != GI_FLAG_EARLY_EOI) gic_c_write_4(sc, GICC_EOIR, irq_active_reg); device_printf(sc->gic_dev, "Stray irq %u disabled\n", irq); } @@ -1087,6 +1089,9 @@ arm_gic_setup_intr(device_t dev, struct intr_irqsrc *isrc, gi->gi_pol = pol; gi->gi_trig = trig; + /* Edge triggered interrupts need an early EOI sent */ + if (gi->gi_pol == INTR_TRIGGER_EDGE) + gi->gi_flags |= GI_FLAG_EARLY_EOI; /* * XXX - In case that per CPU interrupt is going to be enabled in time @@ -1160,7 +1165,7 @@ arm_gic_post_filter(device_t dev, struct intr_irqsrc *isrc) struct gic_irqsrc *gi = (struct gic_irqsrc *)isrc; /* EOI for edge-triggered done earlier. */ - if (gi->gi_trig == INTR_TRIGGER_EDGE) + if ((gi->gi_flags & GI_FLAG_EARLY_EOI) == GI_FLAG_EARLY_EOI) return; arm_irq_memory_barrier(0); From 41b610a8ee6b7b266f0f23c3a6d50ae7b80d0210 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 14:30:40 +0000 Subject: [PATCH 114/143] arm: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/arm/arm/nexus.c | 2 +- sys/arm/arm/pmap-v4.c | 4 ++-- sys/arm/arm/pmap-v6.c | 6 +++--- sys/arm/at91/at91_mci.c | 6 +++--- sys/arm/at91/at91_pio.c | 6 +++--- sys/arm/at91/at91_pmc.c | 2 +- sys/arm/at91/at91_rtc.c | 6 +++--- sys/arm/at91/at91_ssc.c | 6 +++--- sys/arm/at91/at91_twi.c | 6 +++--- sys/arm/at91/if_ate.c | 2 +- sys/arm/cavium/cns11xx/if_ece.c | 6 +++--- sys/arm/xscale/ixp425/ixp425_qmgr.c | 2 +- sys/arm64/arm64/nexus.c | 2 +- 13 files changed, 28 insertions(+), 28 deletions(-) diff --git a/sys/arm/arm/nexus.c b/sys/arm/arm/nexus.c index b718c1d9133a..81f7b020f3e3 100644 --- a/sys/arm/arm/nexus.c +++ b/sys/arm/arm/nexus.c @@ -234,7 +234,7 @@ nexus_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) + if (rv == NULL) return (NULL); rman_set_rid(rv, *rid); diff --git a/sys/arm/arm/pmap-v4.c b/sys/arm/arm/pmap-v4.c index 529e9f1d4518..2d9a941f9bf7 100644 --- a/sys/arm/arm/pmap-v4.c +++ b/sys/arm/arm/pmap-v4.c @@ -265,7 +265,7 @@ void (*pmap_copy_page_offs_func)(vm_paddr_t a_phys, int cnt); void (*pmap_zero_page_func)(vm_paddr_t, int, int); -struct msgbuf *msgbufp = 0; +struct msgbuf *msgbufp = NULL; /* * Crashdump maps. @@ -842,7 +842,7 @@ pmap_alloc_l2_bucket(pmap_t pm, vm_offset_t va) ptep = uma_zalloc(l2zone, M_NOWAIT); rw_wlock(&pvh_global_lock); PMAP_LOCK(pm); - if (l2b->l2b_kva != 0) { + if (l2b->l2b_kva != NULL) { /* We lost the race. */ l2->l2_occupancy--; uma_zfree(l2zone, ptep); diff --git a/sys/arm/arm/pmap-v6.c b/sys/arm/arm/pmap-v6.c index 609b291c1f60..9fb0b20be101 100644 --- a/sys/arm/arm/pmap-v6.c +++ b/sys/arm/arm/pmap-v6.c @@ -310,15 +310,15 @@ static pt2_entry_t *CMAP3; static caddr_t CADDR3; caddr_t _tmppt = 0; -struct msgbuf *msgbufp = 0; /* XXX move it to machdep.c */ +struct msgbuf *msgbufp = NULL; /* XXX move it to machdep.c */ /* * Crashdump maps. */ static caddr_t crashdumpmap; -static pt2_entry_t *PMAP1 = 0, *PMAP2; -static pt2_entry_t *PADDR1 = 0, *PADDR2; +static pt2_entry_t *PMAP1 = NULL, *PMAP2; +static pt2_entry_t *PADDR1 = NULL, *PADDR2; #ifdef DDB static pt2_entry_t *PMAP3; static pt2_entry_t *PADDR3; diff --git a/sys/arm/at91/at91_mci.c b/sys/arm/at91/at91_mci.c index ba6040f68179..cf884b93019f 100644 --- a/sys/arm/at91/at91_mci.c +++ b/sys/arm/at91/at91_mci.c @@ -526,16 +526,16 @@ at91_mci_deactivate(device_t dev) sc = device_get_softc(dev); if (sc->intrhand) bus_teardown_intr(dev, sc->irq_res, sc->intrhand); - sc->intrhand = 0; + sc->intrhand = NULL; bus_generic_detach(sc->dev); if (sc->mem_res) bus_release_resource(dev, SYS_RES_MEMORY, rman_get_rid(sc->mem_res), sc->mem_res); - sc->mem_res = 0; + sc->mem_res = NULL; if (sc->irq_res) bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq_res), sc->irq_res); - sc->irq_res = 0; + sc->irq_res = NULL; return; } diff --git a/sys/arm/at91/at91_pio.c b/sys/arm/at91/at91_pio.c index 0de46c5b9ff1..0d9bd46a4215 100644 --- a/sys/arm/at91/at91_pio.c +++ b/sys/arm/at91/at91_pio.c @@ -240,16 +240,16 @@ at91_pio_deactivate(device_t dev) sc = device_get_softc(dev); if (sc->intrhand) bus_teardown_intr(dev, sc->irq_res, sc->intrhand); - sc->intrhand = 0; + sc->intrhand = NULL; bus_generic_detach(sc->dev); if (sc->mem_res) bus_release_resource(dev, SYS_RES_MEMORY, rman_get_rid(sc->mem_res), sc->mem_res); - sc->mem_res = 0; + sc->mem_res = NULL; if (sc->irq_res) bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq_res), sc->irq_res); - sc->irq_res = 0; + sc->irq_res = NULL; } static void diff --git a/sys/arm/at91/at91_pmc.c b/sys/arm/at91/at91_pmc.c index 16f62ec14331..e93e3b731b4c 100644 --- a/sys/arm/at91/at91_pmc.c +++ b/sys/arm/at91/at91_pmc.c @@ -636,7 +636,7 @@ at91_pmc_deactivate(device_t dev) if (sc->mem_res) bus_release_resource(dev, SYS_RES_IOPORT, rman_get_rid(sc->mem_res), sc->mem_res); - sc->mem_res = 0; + sc->mem_res = NULL; } static int diff --git a/sys/arm/at91/at91_rtc.c b/sys/arm/at91/at91_rtc.c index 6ed044abfea3..7bb80b94bd1d 100644 --- a/sys/arm/at91/at91_rtc.c +++ b/sys/arm/at91/at91_rtc.c @@ -232,18 +232,18 @@ at91_rtc_deactivate(device_t dev) WR4(sc, RTC_IDR, 0xffffffff); if (sc->intrhand) bus_teardown_intr(dev, sc->irq_res, sc->intrhand); - sc->intrhand = 0; + sc->intrhand = NULL; #endif bus_generic_detach(sc->dev); if (sc->mem_res) bus_release_resource(dev, SYS_RES_MEMORY, rman_get_rid(sc->mem_res), sc->mem_res); - sc->mem_res = 0; + sc->mem_res = NULL; #ifdef AT91_RTC_USE_INTERRUPTS if (sc->irq_res) bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq_res), sc->irq_res); - sc->irq_res = 0; + sc->irq_res = NULL; #endif return; } diff --git a/sys/arm/at91/at91_ssc.c b/sys/arm/at91/at91_ssc.c index 8a32f55d42b2..d79020b8b493 100644 --- a/sys/arm/at91/at91_ssc.c +++ b/sys/arm/at91/at91_ssc.c @@ -193,16 +193,16 @@ at91_ssc_deactivate(device_t dev) sc = device_get_softc(dev); if (sc->intrhand) bus_teardown_intr(dev, sc->irq_res, sc->intrhand); - sc->intrhand = 0; + sc->intrhand = NULL; bus_generic_detach(sc->dev); if (sc->mem_res) bus_release_resource(dev, SYS_RES_IOPORT, rman_get_rid(sc->mem_res), sc->mem_res); - sc->mem_res = 0; + sc->mem_res = NULL; if (sc->irq_res) bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq_res), sc->irq_res); - sc->irq_res = 0; + sc->irq_res = NULL; return; } diff --git a/sys/arm/at91/at91_twi.c b/sys/arm/at91/at91_twi.c index f9a7294e4044..28676fc7cd85 100644 --- a/sys/arm/at91/at91_twi.c +++ b/sys/arm/at91/at91_twi.c @@ -216,16 +216,16 @@ at91_twi_deactivate(device_t dev) sc = device_get_softc(dev); if (sc->intrhand) bus_teardown_intr(dev, sc->irq_res, sc->intrhand); - sc->intrhand = 0; + sc->intrhand = NULL; bus_generic_detach(sc->dev); if (sc->mem_res) bus_release_resource(dev, SYS_RES_MEMORY, rman_get_rid(sc->mem_res), sc->mem_res); - sc->mem_res = 0; + sc->mem_res = NULL; if (sc->irq_res) bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq_res), sc->irq_res); - sc->irq_res = 0; + sc->irq_res = NULL; return; } diff --git a/sys/arm/at91/if_ate.c b/sys/arm/at91/if_ate.c index ac200b4a05b2..082b24f3fdfe 100644 --- a/sys/arm/at91/if_ate.c +++ b/sys/arm/at91/if_ate.c @@ -1184,7 +1184,7 @@ atestart_locked(struct ifnet *ifp) } IFQ_DRV_DEQUEUE(&ifp->if_snd, m); - if (m == 0) + if (m == NULL) break; e = bus_dmamap_load_mbuf_sg(sc->mtag, sc->tx_map[sc->txhead], m, diff --git a/sys/arm/cavium/cns11xx/if_ece.c b/sys/arm/cavium/cns11xx/if_ece.c index 20bc07e7167f..2ae3d22d6637 100644 --- a/sys/arm/cavium/cns11xx/if_ece.c +++ b/sys/arm/cavium/cns11xx/if_ece.c @@ -1064,8 +1064,8 @@ clear_mac_entries(struct ece_softc *ec, int include_this_mac) struct mac_list * current; char mac[ETHER_ADDR_LEN]; - current = 0; - mac_list_header = 0; + current = NULL; + mac_list_header = NULL; table_end = read_mac_entry(ec, mac, 1); while (!table_end) { @@ -1608,7 +1608,7 @@ ece_encap(struct ece_softc *sc, struct mbuf *m0) struct ifnet *ifp; bus_dma_segment_t segs[MAX_FRAGMENT]; bus_dmamap_t mapp; - eth_tx_desc_t *desc = 0; + eth_tx_desc_t *desc = NULL; int csum_flags; int desc_no; int error; diff --git a/sys/arm/xscale/ixp425/ixp425_qmgr.c b/sys/arm/xscale/ixp425/ixp425_qmgr.c index cb6c8defc948..822623c12ccb 100644 --- a/sys/arm/xscale/ixp425/ixp425_qmgr.c +++ b/sys/arm/xscale/ixp425/ixp425_qmgr.c @@ -355,7 +355,7 @@ ixpqmgr_qconfig(int qId, int qEntries, int ne, int nf, int srcSel, if (cb == NULL) { /* Reset to dummy callback */ qi->cb = dummyCallback; - qi->cbarg = 0; + qi->cbarg = NULL; } else { qi->cb = cb; qi->cbarg = cbarg; diff --git a/sys/arm64/arm64/nexus.c b/sys/arm64/arm64/nexus.c index f48a7aab0a96..ec714095a671 100644 --- a/sys/arm64/arm64/nexus.c +++ b/sys/arm64/arm64/nexus.c @@ -250,7 +250,7 @@ nexus_alloc_resource(device_t bus, device_t child, int type, int *rid, } rv = rman_reserve_resource(rm, start, end, count, flags, child); - if (rv == 0) + if (rv == NULL) return (NULL); rman_set_rid(rv, *rid); From 9e297f96d4f434b0940d693e1005b550a74faea8 Mon Sep 17 00:00:00 2001 From: Konstantin Belousov Date: Fri, 15 Apr 2016 14:36:38 +0000 Subject: [PATCH 115/143] Always calculate divisor for the counter mode of LAPIC timer. Even if initially configured in the TSC deadline mode, eventtimer subsystem can be switched to periodic, and then DCR register is loaded with unitialized value. Reset the LAPIC eventtimer frequency and min/max periods when changing between deadline and counted periodic modes. Reported and tested by: Vladimir Zakharov Sponsored by: The FreeBSD Foundation --- sys/x86/x86/local_apic.c | 49 ++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 15 deletions(-) diff --git a/sys/x86/x86/local_apic.c b/sys/x86/x86/local_apic.c index 5830b7710269..854bda44741e 100644 --- a/sys/x86/x86/local_apic.c +++ b/sys/x86/x86/local_apic.c @@ -170,7 +170,7 @@ vm_paddr_t lapic_paddr; int x2apic_mode; int lapic_eoi_suppression; static int lapic_timer_tsc_deadline; -static u_long lapic_timer_divisor; +static u_long lapic_timer_divisor, count_freq; static struct eventtimer lapic_et; #ifdef SMP static uint64_t lapic_ipi_wait_mult; @@ -814,20 +814,46 @@ lapic_calibrate_initcount(struct eventtimer *et, struct lapic *la) printf("lapic: Divisor %lu, Frequency %lu Hz\n", lapic_timer_divisor, value); } - et->et_frequency = value; + count_freq = value; } static void lapic_calibrate_deadline(struct eventtimer *et, struct lapic *la __unused) { - et->et_frequency = tsc_freq; if (bootverbose) { printf("lapic: deadline tsc mode, Frequency %ju Hz\n", - (uintmax_t)et->et_frequency); + (uintmax_t)tsc_freq); } } +static void +lapic_change_mode(struct eventtimer *et, struct lapic *la, + enum lat_timer_mode newmode) +{ + + if (la->la_timer_mode == newmode) + return; + switch (newmode) { + case LAT_MODE_PERIODIC: + lapic_timer_set_divisor(lapic_timer_divisor); + et->et_frequency = count_freq; + break; + case LAT_MODE_DEADLINE: + et->et_frequency = tsc_freq; + break; + case LAT_MODE_ONESHOT: + lapic_timer_set_divisor(lapic_timer_divisor); + et->et_frequency = count_freq; + break; + default: + panic("lapic_change_mode %d", newmode); + } + la->la_timer_mode = newmode; + et->et_min_period = (0x00000002LLU << 32) / et->et_frequency; + et->et_max_period = (0xfffffffeLLU << 32) / et->et_frequency; +} + static int lapic_et_start(struct eventtimer *et, sbintime_t first, sbintime_t period) { @@ -835,28 +861,21 @@ lapic_et_start(struct eventtimer *et, sbintime_t first, sbintime_t period) la = &lapics[PCPU_GET(apic_id)]; if (et->et_frequency == 0) { + lapic_calibrate_initcount(et, la); if (lapic_timer_tsc_deadline) lapic_calibrate_deadline(et, la); - else - lapic_calibrate_initcount(et, la); - et->et_min_period = (0x00000002LLU << 32) / et->et_frequency; - et->et_max_period = (0xfffffffeLLU << 32) / et->et_frequency; } if (period != 0) { - if (la->la_timer_mode == LAT_MODE_UNDEF) - lapic_timer_set_divisor(lapic_timer_divisor); - la->la_timer_mode = LAT_MODE_PERIODIC; + lapic_change_mode(et, la, LAT_MODE_PERIODIC); la->la_timer_period = ((uint32_t)et->et_frequency * period) >> 32; lapic_timer_periodic(la); } else if (lapic_timer_tsc_deadline) { - la->la_timer_mode = LAT_MODE_DEADLINE; + lapic_change_mode(et, la, LAT_MODE_DEADLINE); la->la_timer_period = (et->et_frequency * first) >> 32; lapic_timer_deadline(la); } else { - if (la->la_timer_mode == LAT_MODE_UNDEF) - lapic_timer_set_divisor(lapic_timer_divisor); - la->la_timer_mode = LAT_MODE_ONESHOT; + lapic_change_mode(et, la, LAT_MODE_ONESHOT); la->la_timer_period = ((uint32_t)et->et_frequency * first) >> 32; lapic_timer_oneshot(la); From 3e4b91800ae793f6d701cb203c19ec793ae82722 Mon Sep 17 00:00:00 2001 From: Stanislav Galabov Date: Fri, 15 Apr 2016 15:20:41 +0000 Subject: [PATCH 116/143] In order to build a kernel with one of these configs the user should do the following: 1. Give the appropriate board dts file to be used by either: 1.1. edit the SoC kernel config required (e.g., MT7620A_FDT) and include the required FDT_DTS_FILE makeoption; or 1.2. simply supply FDT_DTS_FILE="xx.dts" on the command line when building the kernel Of course, the user can also create a completely new kernel config to match the desired board and include the SoC kernel config from within it. If required, edit the MEDIATEK config file, which includes optional drivers and comment out the unneeded ones. 2.1. this would only make sense if kernel size is a concern. Even if we build the kernel with all drivers, if we lzma it and package it as a uImage, its size is still around 1.1MiB. The user will have to choose a dts file (or create a new one) from sys/gnu/dts/mips , where all Mediatek/Ralink dts files will be imported via a later revision. Approved by: adrian (mentor) Sponsored by: Smartcom - Bulgaria AD Differential Revision: https://reviews.freebsd.org/D5966 --- sys/mips/conf/MEDIATEK | 81 +++++++++++++++++++++++++++++++++ sys/mips/conf/MEDIATEK_BASE | 89 +++++++++++++++++++++++++++++++++++++ sys/mips/conf/MT7620A_FDT | 30 +++++++++++++ sys/mips/conf/MT7620N_FDT | 30 +++++++++++++ sys/mips/conf/MT7621_FDT | 30 +++++++++++++ sys/mips/conf/MT7628_FDT | 30 +++++++++++++ sys/mips/conf/RT3050_FDT | 31 +++++++++++++ sys/mips/conf/RT3352_FDT | 30 +++++++++++++ sys/mips/conf/RT3883_FDT | 30 +++++++++++++ sys/mips/conf/RT5350_FDT | 30 +++++++++++++ 10 files changed, 411 insertions(+) create mode 100644 sys/mips/conf/MEDIATEK create mode 100644 sys/mips/conf/MEDIATEK_BASE create mode 100644 sys/mips/conf/MT7620A_FDT create mode 100644 sys/mips/conf/MT7620N_FDT create mode 100644 sys/mips/conf/MT7621_FDT create mode 100644 sys/mips/conf/MT7628_FDT create mode 100644 sys/mips/conf/RT3050_FDT create mode 100644 sys/mips/conf/RT3352_FDT create mode 100644 sys/mips/conf/RT3883_FDT create mode 100644 sys/mips/conf/RT5350_FDT diff --git a/sys/mips/conf/MEDIATEK b/sys/mips/conf/MEDIATEK new file mode 100644 index 000000000000..4cf82258893a --- /dev/null +++ b/sys/mips/conf/MEDIATEK @@ -0,0 +1,81 @@ +# +# MEDIATEK -- Kernel configuration file for FreeBSD/MIPS Mediatek/Ralink SoCs +# +# This includes all the configurable parts of the kernel. Please read through +# the sections below and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# Don't build any modules by default +makeoptions MODULES_OVERRIDE="" + +# +# Default rootfs device configuration, should be changed to suit target board +# +options ROOTDEVNAME=\"ufs:md0.uzip\" + +# +# Optional drivers section +# +# What follows is optional support drivers for the Mediatek SoCs. +# The kernel can be compiled without them if size is a concern. +# All optional drivers are built by default. +# + +# Support geom_uzip(4) compressed disk images +device geom_uzip +options GEOM_UZIP + +# Support md(4) and md-based rootfs +device md +options MD_ROOT + +# SPI and SPI flash support +device spibus +device mx25l + +# GPIO and gpioled support +device gpio +device gpioled + +# PCI support +device pci + +# +# USB (ehci, ohci, xhci, otg) support. Unneeded drivers can be commented in +# order to lower kernel size. See below for driver SoC support. +# +# For all SoCs that require USB support +device usb +# For RT3050, RT3052 and RT3350 SoCs +device dwcotg +# For RT3352, RT3662, RT3883, RT5350, MT7620, MT7628 and MT7688 +device ohci +device ehci +# For MT7621, or cases where the target board has a XHCI controller on PCI +# (for example Asus RT-N65U) +device xhci + +# USB umass(4) storage and da(4) support +device umass +device da + +# ahci(4) and ada(4) support, depends on PCI +device ahci +device ada + +# CAM support, required if either umass(4) or ahci(4) is enabled above +device pass +device scbus + +# Ethernet, BPS and bridge support +device rt +device bpf +device if_bridge + +# Extres +device ext_resources +device clk diff --git a/sys/mips/conf/MEDIATEK_BASE b/sys/mips/conf/MEDIATEK_BASE new file mode 100644 index 000000000000..5e6c0ad7befb --- /dev/null +++ b/sys/mips/conf/MEDIATEK_BASE @@ -0,0 +1,89 @@ +# +# MEDIATEK_BASE -- Base kernel configuration file for FreeBSD/MIPS +# Mediatek/Ralink SoCs. +# +# This includes all the required drivers for the SoCs. +# Ususally, users should not build this kernel configuration. It is provided +# only as a minimum base, from which customizations can be made. Please look +# at MEDIATEK kernel configuration for customization details. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# Include the standard file list for Mediatek SoCs. +files "../mediatek/files.mtk" + +# Building a mips/mipsel kernel +machine mips mipsel + +# Little-endian machine +makeoptions MIPS_LITTLE_ENDIAN=defined + +# Default kernel load address +makeoptions KERNLOADADDR=0x80001000 + +# Mediatek/Ralink SoC support depends on FDT (with static DTB for the moment) +options FDT +options FDT_DTB_STATIC + +# We rely on MIPS_INTRNG code +options MIPS_INTRNG +options MIPS_NIRQ=256 + +# We rely on NEW_PCIB code +options NEW_PCIB + +# Build kernel with gdb(1) debug symbols +makeoptions DEBUG=-g + +# Support for DDB and KDB +options DDB +options KDB + +# Debugging for use in -current +options INVARIANTS +options INVARIANT_SUPPORT +options WITNESS +options WITNESS_SKIPSPIN +options DEBUG_REDZONE +options DEBUG_MEMGUARD + +# For small memory footprints +options VM_KMEM_SIZE_SCALE=1 + +# General options, including scheduler, etc. +options SCHED_ULE # ULE scheduler +options INET # InterNETworking +#options INET6 # IPv6 +options PSEUDOFS # Pseude-filesystem framework +options FFS # Berkeley Fast Filesystem +#options SOFTUPDATES # Enable FFS soft updates support +#options UFS_ACL # Support for access control lists +#options UFS_DIRHASH # Improve big directory performance +#options MSDOSFS # Enable support for MSDOS filesystems +options _KPOSIX_PRIORITY_SCHEDULING # Posix P1003_1B real-time ext. + +# +# Standard drivers section +# +# The drivers in the following section are required in order to successfully +# compile the kernel. +# + +# FDT clock and pinctrl framework +device fdt_clock +device fdt_pinctrl + +# UART support +device uart + +# random support +device random + +# loop device support +device loop + +# ether device support +device ether diff --git a/sys/mips/conf/MT7620A_FDT b/sys/mips/conf/MT7620A_FDT new file mode 100644 index 000000000000..8468304073e6 --- /dev/null +++ b/sys/mips/conf/MT7620A_FDT @@ -0,0 +1,30 @@ +# +# MT7620A_FDT -- Kernel configuration file for FreeBSD/MIPS MT7620A SoC +# +# This includes all the configurable parts of the kernel. Please read through +# MEDIATEK kernel config and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# +# FDT_DTS_FILE should be modified to suit the target board type. +# +#makeoptions FDT_DTS_FILE=MT7620a.dts + +# +# The user should never have to edit what's below this line. +# If customizations are needed, they should be done to the MEDIATEK kernel +# configuration. +# + +# Start with a base configuration +include MEDIATEK_BASE + +ident MT7620A +cpu CPU_MIPS24K + +# Include optional configuration (to be edited by the user if needed) +include MEDIATEK diff --git a/sys/mips/conf/MT7620N_FDT b/sys/mips/conf/MT7620N_FDT new file mode 100644 index 000000000000..64222df37b2e --- /dev/null +++ b/sys/mips/conf/MT7620N_FDT @@ -0,0 +1,30 @@ +# +# MT7620N_FDT -- Kernel configuration file for FreeBSD/MIPS MT7620N SoC +# +# This includes all the configurable parts of the kernel. Please read through +# MEDIATEK kernel config and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# +# FDT_DTS_FILE should be modified to suit the target board type. +# +#makeoptions FDT_DTS_FILE=WRTNODE.dts + +# +# The user should never have to edit what's below this line. +# If customizations are needed, they should be done to the MEDIATEK kernel +# configuration. +# + +# Start with a base configuration +include MEDIATEK_BASE + +ident MT7620N +cpu CPU_MIPS24K + +# Include optional configuration (to be edited by the user if needed) +include MEDIATEK diff --git a/sys/mips/conf/MT7621_FDT b/sys/mips/conf/MT7621_FDT new file mode 100644 index 000000000000..a80c953017dc --- /dev/null +++ b/sys/mips/conf/MT7621_FDT @@ -0,0 +1,30 @@ +# +# MT7621_FDT -- Kernel configuration file for FreeBSD/MIPS MT7621 SoC +# +# This includes all the configurable parts of the kernel. Please read through +# MEDIATEK kernel config and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# +# FDT_DTS_FILE should be modified to suit the target board type. +# +#makeoptions FDT_DTS_FILE=ZBT-WG2626.dts + +# +# The user should never have to edit what's below this line. +# If customizations are needed, they should be done to the MEDIATEK kernel +# configuration. +# + +# Start with a base configuration +include MEDIATEK_BASE + +ident MT7621 +cpu CPU_MIPS1004K + +# Include optional configuration (to be edited by the user if needed) +include MEDIATEK diff --git a/sys/mips/conf/MT7628_FDT b/sys/mips/conf/MT7628_FDT new file mode 100644 index 000000000000..bbffa65d8246 --- /dev/null +++ b/sys/mips/conf/MT7628_FDT @@ -0,0 +1,30 @@ +# +# MT7628_FDT -- Kernel configuration file for FreeBSD/MIPS MT7628/MT7688 SoCs +# +# This includes all the configurable parts of the kernel. Please read through +# MEDIATEK kernel config and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# +# FDT_DTS_FILE should be modified to suit the target board type. +# +#makeoptions FDT_DTS_FILE=MT7628.dts + +# +# The user should never have to edit what's below this line. +# If customizations are needed, they should be done to the MEDIATEK kernel +# configuration. +# + +# Start with a base configuration +include MEDIATEK_BASE + +ident MT7628 +cpu CPU_MIPS24K + +# Include optional configuration (to be edited by the user if needed) +include MEDIATEK diff --git a/sys/mips/conf/RT3050_FDT b/sys/mips/conf/RT3050_FDT new file mode 100644 index 000000000000..435020f9a81a --- /dev/null +++ b/sys/mips/conf/RT3050_FDT @@ -0,0 +1,31 @@ +# +# RT3050_FDT -- Kernel configuration file for FreeBSD/MIPS RT3050/RT3052/RT3350 +# SoCs +# +# This includes all the configurable parts of the kernel. Please read through +# MEDIATEK kernel config and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# +# FDT_DTS_FILE should be modified to suit the target board type. +# +#makeoptions FDT_DTS_FILE=DIR-600-B1.dts + +# +# The user should never have to edit what's below this line. +# If customizations are needed, they should be done to the MEDIATEK kernel +# configuration. +# + +# Start with a base configuration +include MEDIATEK_BASE + +ident RT3050 +cpu CPU_MIPS24K + +# Include optional configuration (to be edited by the user if needed) +include MEDIATEK diff --git a/sys/mips/conf/RT3352_FDT b/sys/mips/conf/RT3352_FDT new file mode 100644 index 000000000000..ec33b9c5c7b7 --- /dev/null +++ b/sys/mips/conf/RT3352_FDT @@ -0,0 +1,30 @@ +# +# RT3352_FDT -- Kernel configuration file for FreeBSD/MIPS RT3352 SoC +# +# This includes all the configurable parts of the kernel. Please read through +# MEDIATEK kernel config and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# +# FDT_DTS_FILE should be modified to suit the target board type. +# +#makeoptions FDT_DTS_FILE=DIR-615-H1.dts + +# +# The user should never have to edit what's below this line. +# If customizations are needed, they should be done to the MEDIATEK kernel +# configuration. +# + +# Start with a base configuration +include MEDIATEK_BASE + +ident RT3352 +cpu CPU_MIPS24K + +# Include optional configuration (to be edited by the user if needed) +include MEDIATEK diff --git a/sys/mips/conf/RT3883_FDT b/sys/mips/conf/RT3883_FDT new file mode 100644 index 000000000000..6229e2c58d21 --- /dev/null +++ b/sys/mips/conf/RT3883_FDT @@ -0,0 +1,30 @@ +# +# RT3883_FDT -- Kernel configuration file for FreeBSD/MIPS RT3662/RT3883 SoCs +# +# This includes all the configurable parts of the kernel. Please read through +# MEDIATEK kernel config and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# +# FDT_DTS_FILE should be modified to suit the target board type. +# +#makeoptions FDT_DTS_FILE=DIR-645.dts + +# +# The user should never have to edit what's below this line. +# If customizations are needed, they should be done to the MEDIATEK kernel +# configuration. +# + +# Start with a base configuration +include MEDIATEK_BASE + +ident RT3883 +cpu CPU_MIPS74K + +# Include optional configuration (to be edited by the user if needed) +include MEDIATEK diff --git a/sys/mips/conf/RT5350_FDT b/sys/mips/conf/RT5350_FDT new file mode 100644 index 000000000000..827bdd30b4e1 --- /dev/null +++ b/sys/mips/conf/RT5350_FDT @@ -0,0 +1,30 @@ +# +# RT5350_FDT -- Kernel configuration file for FreeBSD/MIPS RT5350 SoC +# +# This includes all the configurable parts of the kernel. Please read through +# MEDIATEK kernel config and customize the options to fit your board if needed. +# +# $FreeBSD$ +# + +#NO_UNIVERSE + +# +# FDT_DTS_FILE should be modified to suit the target board type. +# +#makeoptions FDT_DTS_FILE=DIR-300-B7.dts + +# +# The user should never have to edit what's below this line. +# If customizations are needed, they should be done to the MEDIATEK kernel +# configuration. +# + +# Start with a base configuration +include MEDIATEK_BASE + +ident RT5350 +cpu CPU_MIPS24K + +# Include optional configuration (to be edited by the user if needed) +include MEDIATEK From 913b41b84ed8b0814ed554ecb29f1c73131a322b Mon Sep 17 00:00:00 2001 From: Stanislav Galabov Date: Fri, 15 Apr 2016 15:22:28 +0000 Subject: [PATCH 117/143] Remove unneeded initialization in mtk_xhci.c This is actually initialized properly within xhci.c, so it's better to not initialize it in mtk_xhci.c Approved by: adrian (mentor) Sponsored by: Smartcom - Bulgaria AD Differential Revision: https://reviews.freebsd.org/D5935 --- sys/mips/mediatek/mtk_xhci.c | 1 - 1 file changed, 1 deletion(-) diff --git a/sys/mips/mediatek/mtk_xhci.c b/sys/mips/mediatek/mtk_xhci.c index 08993072c35f..78328bb4f040 100644 --- a/sys/mips/mediatek/mtk_xhci.c +++ b/sys/mips/mediatek/mtk_xhci.c @@ -99,7 +99,6 @@ mtk_xhci_fdt_attach(device_t self) sc->sc_bus.parent = self; sc->sc_bus.devices = sc->sc_devices; sc->sc_bus.devices_max = XHCI_MAX_DEVICES; - sc->sc_bus.dma_bits = 32; rid = 0; sc->sc_io_res = bus_alloc_resource_any(self, SYS_RES_MEMORY, &rid, From c1300b5e373827a385fd1599abf2b151eefcb28c Mon Sep 17 00:00:00 2001 From: Stanislav Galabov Date: Fri, 15 Apr 2016 15:24:42 +0000 Subject: [PATCH 118/143] Mediatek/Ralink: Get our drivers closer to OpenWRT dts definitions This revision gets our Mediatek/Ralink drivers closer to OpenWRT's dts definitions, so we can reuse them with less modifications later in order to bring support for a lot of boards at once. Approved by: adrian (mentor) Sponsored by: Smartcom - Bulgaria AD Differential Revision: https://reviews.freebsd.org/D5961 --- sys/dev/rt/if_rt.c | 15 ++++++------ sys/mips/mediatek/mtk_ehci.c | 2 +- sys/mips/mediatek/mtk_gpio_v1.c | 4 ++-- sys/mips/mediatek/mtk_gpio_v2.c | 6 ++--- sys/mips/mediatek/mtk_intr_gic.c | 4 ++-- sys/mips/mediatek/mtk_ohci.c | 2 +- sys/mips/mediatek/mtk_pcie.c | 41 +++++++++++++++++++------------- sys/mips/mediatek/mtk_soc.c | 1 + sys/mips/mediatek/mtk_usb_phy.c | 5 ++-- sys/mips/mediatek/mtk_xhci.c | 2 +- 10 files changed, 46 insertions(+), 36 deletions(-) diff --git a/sys/dev/rt/if_rt.c b/sys/dev/rt/if_rt.c index fd042fe70251..5b4dc85d043b 100644 --- a/sys/dev/rt/if_rt.c +++ b/sys/dev/rt/if_rt.c @@ -99,13 +99,14 @@ __FBSDID("$FreeBSD$"); #ifdef FDT /* more specific and new models should go first */ static const struct ofw_compat_data rt_compat_data[] = { - { "ralink,rt3050-eth", RT_CHIPID_RT3050 }, - { "ralink,rt3352-eth", RT_CHIPID_RT3050 }, - { "ralink,rt3883-eth", RT_CHIPID_RT3050 }, - { "ralink,rt5350-eth", RT_CHIPID_RT5350 }, - { "ralink,mt7620a-eth", RT_CHIPID_MT7620 }, - { "ralink,mt7621-eth", RT_CHIPID_MT7621 }, - { NULL, 0 } + { "ralink,rt3050-eth", RT_CHIPID_RT3050 }, + { "ralink,rt3352-eth", RT_CHIPID_RT3050 }, + { "ralink,rt3883-eth", RT_CHIPID_RT3050 }, + { "ralink,rt5350-eth", RT_CHIPID_RT5350 }, + { "ralink,mt7620a-eth", RT_CHIPID_MT7620 }, + { "ralink,mt7621-eth", RT_CHIPID_MT7621 }, + { "mediatek,mt7621-eth", RT_CHIPID_MT7621 }, + { NULL, 0 } }; #endif diff --git a/sys/mips/mediatek/mtk_ehci.c b/sys/mips/mediatek/mtk_ehci.c index 109a32a8841e..acc30eb028cd 100644 --- a/sys/mips/mediatek/mtk_ehci.c +++ b/sys/mips/mediatek/mtk_ehci.c @@ -78,7 +78,7 @@ ehci_fdt_probe(device_t self) if (!ofw_bus_status_okay(self)) return (ENXIO); - if (!ofw_bus_is_compatible(self, "ralink,rt3xxx-ehci")) + if (!ofw_bus_is_compatible(self, "generic-ehci")) return (ENXIO); device_set_desc(self, EHCI_HC_DEVSTR); diff --git a/sys/mips/mediatek/mtk_gpio_v1.c b/sys/mips/mediatek/mtk_gpio_v1.c index 29b2258414f1..ad3a0fc1dcd4 100644 --- a/sys/mips/mediatek/mtk_gpio_v1.c +++ b/sys/mips/mediatek/mtk_gpio_v1.c @@ -281,8 +281,8 @@ mtk_gpio_attach(device_t dev) sc->do_remap = 0; } - if (OF_hasprop(node, "mtk,num-pins") && (OF_getencprop(node, - "mtk,num-pins", &num_pins, sizeof(num_pins)) >= 0)) + if (OF_hasprop(node, "ralink,num-gpios") && (OF_getencprop(node, + "ralink,num-gpios", &num_pins, sizeof(num_pins)) >= 0)) sc->num_pins = num_pins; else sc->num_pins = MTK_GPIO_PINS; diff --git a/sys/mips/mediatek/mtk_gpio_v2.c b/sys/mips/mediatek/mtk_gpio_v2.c index 282b112e7579..c7c0326c1166 100644 --- a/sys/mips/mediatek/mtk_gpio_v2.c +++ b/sys/mips/mediatek/mtk_gpio_v2.c @@ -121,8 +121,8 @@ static int mtk_gpio_intr(void *arg); #define GPIO_PIORESET(_sc) GPIO_REG((_sc), 0x0040) static struct ofw_compat_data compat_data[] = { - { "mtk,mt7621-gpio", 1 }, - { "mtk,mt7628-gpio", 1 }, + { "mtk,mt7621-gpio-bank", 1 }, + { "mtk,mt7628-gpio-bank", 1 }, { NULL, 0 } }; @@ -281,7 +281,7 @@ mtk_gpio_attach(device_t dev) else sc->num_pins = MTK_GPIO_PINS; - for (i = 0; i < num_pins; i++) { + for (i = 0; i < sc->num_pins; i++) { sc->pins[i].pin_caps |= GPIO_PIN_INPUT | GPIO_PIN_OUTPUT | GPIO_PIN_INVIN | GPIO_PIN_INVOUT; sc->pins[i].intr_polarity = INTR_POLARITY_HIGH; diff --git a/sys/mips/mediatek/mtk_intr_gic.c b/sys/mips/mediatek/mtk_intr_gic.c index 3eb6ffcc20c3..ab96cacb2fb1 100644 --- a/sys/mips/mediatek/mtk_intr_gic.c +++ b/sys/mips/mediatek/mtk_intr_gic.c @@ -281,10 +281,10 @@ mtk_gic_map_intr(device_t dev, struct intr_map_data *data, sc = device_get_softc(dev); if (data == NULL || data->type != INTR_MAP_DATA_FDT || - data->fdt.ncells != 1 || data->fdt.cells[0] >= sc->nirqs) + data->fdt.ncells != 3 || data->fdt.cells[1] >= sc->nirqs) return (EINVAL); - *isrcp = GIC_INTR_ISRC(sc, data->fdt.cells[0]); + *isrcp = GIC_INTR_ISRC(sc, data->fdt.cells[1]); return (0); #else return (EINVAL); diff --git a/sys/mips/mediatek/mtk_ohci.c b/sys/mips/mediatek/mtk_ohci.c index 91c98cebddab..0b554e7f799e 100644 --- a/sys/mips/mediatek/mtk_ohci.c +++ b/sys/mips/mediatek/mtk_ohci.c @@ -78,7 +78,7 @@ ohci_fdt_probe(device_t self) if (!ofw_bus_status_okay(self)) return (ENXIO); - if (!ofw_bus_is_compatible(self, "ralink,rt3xxx-ohci")) + if (!ofw_bus_is_compatible(self, "generic-ohci")) return (ENXIO); device_set_desc(self, OHCI_HC_DEVSTR); diff --git a/sys/mips/mediatek/mtk_pcie.c b/sys/mips/mediatek/mtk_pcie.c index e88b9ab92060..66d8add54679 100644 --- a/sys/mips/mediatek/mtk_pcie.c +++ b/sys/mips/mediatek/mtk_pcie.c @@ -99,7 +99,7 @@ struct mtk_pci_range { u_long len; }; -#define FDT_RANGES_CELLS (3 * 2) +#define FDT_RANGES_CELLS ((1 + 2 + 3) * 2) static void mtk_pci_range_dump(struct mtk_pci_range *range) @@ -117,30 +117,33 @@ mtk_pci_ranges_decode(phandle_t node, struct mtk_pci_range *io_space, { struct mtk_pci_range *pci_space; pcell_t ranges[FDT_RANGES_CELLS]; + pcell_t addr_cells, size_cells, par_addr_cells; pcell_t *rangesptr; pcell_t cell0, cell1, cell2; - int tuples, i, rv, len; + int tuple_size, tuples, i, rv, len; /* * Retrieve 'ranges' property. */ - if (!OF_hasprop(node, "ranges")) { - printf("%s: %d\n", __FUNCTION__, 1); + if ((fdt_addrsize_cells(node, &addr_cells, &size_cells)) != 0) return (EINVAL); - } + if (addr_cells != 3 || size_cells != 2) + return (ERANGE); + + par_addr_cells = fdt_parent_addr_cells(node); + if (par_addr_cells != 1) + return (ERANGE); len = OF_getproplen(node, "ranges"); - if (len > sizeof(ranges)) { - printf("%s: %d\n", __FUNCTION__, 2); + if (len > sizeof(ranges)) return (ENOMEM); - } - if (OF_getprop(node, "ranges", ranges, sizeof(ranges)) <= 0) { - printf("%s: %d\n", __FUNCTION__, 3); + if (OF_getprop(node, "ranges", ranges, sizeof(ranges)) <= 0) return (EINVAL); - } - tuples = len / (sizeof(pcell_t) * 3); + tuple_size = sizeof(pcell_t) * (addr_cells + par_addr_cells + + size_cells); + tuples = len / tuple_size; /* * Initialize the ranges so that we don't have to worry about @@ -159,18 +162,21 @@ mtk_pci_ranges_decode(phandle_t node, struct mtk_pci_range *io_space, cell2 = fdt_data_get((void *)rangesptr, 1); rangesptr++; - if (cell0 == 2) { + if (cell0 & 0x02000000) { pci_space = mem_space; - } else if (cell0 == 1) { + } else if (cell0 & 0x01000000) { pci_space = io_space; } else { rv = ERANGE; - printf("%s: %d\n", __FUNCTION__, 4); goto out; } - pci_space->base = cell1; - pci_space->len = cell2; + pci_space->base = fdt_data_get((void *)rangesptr, + par_addr_cells); + rangesptr += par_addr_cells; + + pci_space->len = fdt_data_get((void *)rangesptr, size_cells); + rangesptr += size_cells; } rv = 0; @@ -199,6 +205,7 @@ static struct ofw_compat_data compat_data[] = { { "ralink,rt3883-pcie", MTK_SOC_RT3883 }, { "ralink,mt7620a-pcie", MTK_SOC_MT7620A }, { "ralink,mt7621-pcie", MTK_SOC_MT7621 }, + { "mediatek,mt7621-pci", MTK_SOC_MT7621 }, { "ralink,mt7628-pcie", MTK_SOC_MT7628 }, { "ralink,mt7688-pcie", MTK_SOC_MT7628 }, { NULL, MTK_SOC_UNKNOWN } diff --git a/sys/mips/mediatek/mtk_soc.c b/sys/mips/mediatek/mtk_soc.c index b331467e9d81..5784fec6d7bc 100644 --- a/sys/mips/mediatek/mtk_soc.c +++ b/sys/mips/mediatek/mtk_soc.c @@ -63,6 +63,7 @@ static const struct ofw_compat_data compat_data[] = { { "ralink,mtk7620a-soc", MTK_SOC_MT7620A }, { "ralink,mtk7620n-soc", MTK_SOC_MT7620N }, { "mediatek,mtk7621-soc", MTK_SOC_MT7621 }, + { "mediatek,mt7621-soc", MTK_SOC_MT7621 }, { "ralink,mtk7621-soc", MTK_SOC_MT7621 }, { "ralink,mtk7628an-soc", MTK_SOC_MT7628 }, { "mediatek,mt7628an-soc", MTK_SOC_MT7628 }, diff --git a/sys/mips/mediatek/mtk_usb_phy.c b/sys/mips/mediatek/mtk_usb_phy.c index d400720f34b1..59b1ffd70d9a 100644 --- a/sys/mips/mediatek/mtk_usb_phy.c +++ b/sys/mips/mediatek/mtk_usb_phy.c @@ -84,9 +84,10 @@ static void mtk_usb_phy_mt7621_init(device_t); static void mtk_usb_phy_mt7628_init(device_t); static struct ofw_compat_data compat_data[] = { - { "ralink,mt7620a-usbphy", MTK_SOC_MT7620A }, + { "ralink,mt7620-usbphy", MTK_SOC_MT7620A }, { "ralink,mt7628an-usbphy", MTK_SOC_MT7628 }, - { "ralink,rt3xxx-usbphy", MTK_SOC_RT3352 }, + { "ralink,rt3352-usbphy", MTK_SOC_RT3352 }, + { "ralink,rt3050-usbphy", MTK_SOC_RT3050 }, { NULL, MTK_SOC_UNKNOWN } }; diff --git a/sys/mips/mediatek/mtk_xhci.c b/sys/mips/mediatek/mtk_xhci.c index 78328bb4f040..138a4d4df83d 100644 --- a/sys/mips/mediatek/mtk_xhci.c +++ b/sys/mips/mediatek/mtk_xhci.c @@ -80,7 +80,7 @@ mtk_xhci_fdt_probe(device_t self) if (!ofw_bus_status_okay(self)) return (ENXIO); - if (!ofw_bus_is_compatible(self, "mtk,usb-xhci")) + if (!ofw_bus_is_compatible(self, "mediatek,mt8173-xhci")) return (ENXIO); device_set_desc(self, XHCI_HC_DEVSTR); From 1173c20679475f39bfcbf07a2edde5ee05e197e2 Mon Sep 17 00:00:00 2001 From: Stanislav Galabov Date: Fri, 15 Apr 2016 15:26:31 +0000 Subject: [PATCH 119/143] Make mx25l compatible with jedec,spi-nor as well A lot of dts files define the SPI flashes supported by mx25l as compatible with 'jedec,spi-nor', so we add this to the mx25l compat_data. Approved by: adrian (mentor) Sponsored by: Smartcom - Bulgaria AD Differential Revision: https://reviews.freebsd.org/D5962 --- sys/dev/flash/mx25l.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/sys/dev/flash/mx25l.c b/sys/dev/flash/mx25l.c index 6b71340f2b0d..96fb4a4907a6 100644 --- a/sys/dev/flash/mx25l.c +++ b/sys/dev/flash/mx25l.c @@ -432,6 +432,12 @@ mx25l_set_4b_mode(device_t dev, uint8_t command) return (err); } +static struct ofw_compat_data compat_data[] = { + { "st,m25p", 1 }, + { "jedec,spi-nor", 1 }, + { NULL, 0 }, +}; + static int mx25l_probe(device_t dev) { @@ -439,7 +445,7 @@ mx25l_probe(device_t dev) #ifdef FDT if (!ofw_bus_status_okay(dev)) return (ENXIO); - if (!ofw_bus_is_compatible(dev, "st,m25p")) + if (ofw_bus_search_compatible(dev, compat_data)->ocd_data == 0) return (ENXIO); #endif device_set_desc(dev, "M25Pxx Flash Family"); From fd868a25a88fe8b62b936c55b96bb86c72d30794 Mon Sep 17 00:00:00 2001 From: Stanislav Galabov Date: Fri, 15 Apr 2016 15:28:23 +0000 Subject: [PATCH 120/143] Change the fdt_static_dtb.S dependency fdt_static_dtb.S dependency in sys/conf/files is currently set as: $S/boot/fdt/dts/${MACHINE}/${FDT_DTS_FILE} This is wrong, as what fdt_static_dtb.S actually uses is the DTB file produced from the FDT_DTS_FILE. In addition it also makes using DTS files stored in $S/gnu/dts/${MACHINE}/ impossible. So, change the dependency to "fdt_dtb_file", which seems to be the right option here anyway. Approved by: adrian (mentor) Sponsored by: Smartcom - Bulgaria AD Differential Revision: https://reviews.freebsd.org/D5963 --- sys/conf/files | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/conf/files b/sys/conf/files index 77169fa6316e..6e57021c685a 100644 --- a/sys/conf/files +++ b/sys/conf/files @@ -1443,7 +1443,7 @@ dev/fdt/fdt_pinctrl.c optional fdt fdt_pinctrl dev/fdt/fdt_pinctrl_if.m optional fdt fdt_pinctrl dev/fdt/fdt_slicer.c optional fdt cfi | fdt nand | fdt mx25l dev/fdt/fdt_static_dtb.S optional fdt fdt_dtb_static \ - dependency "$S/boot/fdt/dts/${MACHINE}/${FDT_DTS_FILE}" + dependency "fdt_dtb_file" dev/fdt/simplebus.c optional fdt dev/fe/if_fe.c optional fe dev/fe/if_fe_pccard.c optional fe pccard From 89f8f24077192a86329622eedae0f04ad9c30bf1 Mon Sep 17 00:00:00 2001 From: Stanislav Galabov Date: Fri, 15 Apr 2016 15:36:09 +0000 Subject: [PATCH 121/143] Import Mediatek/Ralink dtsi patches against OpenWRT dtsi files This revision suggests dtsi patches to be used with the original OpenWRT dtsi files so we can re-use what has already been done in OpenWRT for the Mediatek/Ralink SoCs. The only thing that is required after importing this revision should be the following: 1. Import OpenWRT dts/dtsi files into sys/gnu/dts/mips 2. Run the following script in sys/gnu/dts/mips: for f in `ls [mr]t*.dtsi`; do printf "\n#include \n" > $f done This will apply our dtsi patches to OpenWRT's dtsi files and will allow us to re-use dts/dtsi files for ~170 Mediatek/Ralink boards. Currently our drivers are not 100% compatible with OpenWRT's dts files, but they're compatible enough. We can add more functionality in the future that would better leverage the OpenWRT work as well. Approved by: adrian (mentor) Sponsored by: Smartcom - Bulgaria AD Differential Revision: https://reviews.freebsd.org/D5965 --- sys/boot/fdt/dts/mips/fbsd-mt7620a.dtsi | 52 ++++++++++++ sys/boot/fdt/dts/mips/fbsd-mt7620n.dtsi | 38 +++++++++ sys/boot/fdt/dts/mips/fbsd-mt7621.dtsi | 102 +++++++++++++++++++++++ sys/boot/fdt/dts/mips/fbsd-mt7628an.dtsi | 88 +++++++++++++++++++ sys/boot/fdt/dts/mips/fbsd-rt2880.dtsi | 33 ++++++++ sys/boot/fdt/dts/mips/fbsd-rt3050.dtsi | 41 +++++++++ sys/boot/fdt/dts/mips/fbsd-rt3352.dtsi | 38 +++++++++ sys/boot/fdt/dts/mips/fbsd-rt3883.dtsi | 50 +++++++++++ sys/boot/fdt/dts/mips/fbsd-rt5350.dtsi | 38 +++++++++ 9 files changed, 480 insertions(+) create mode 100644 sys/boot/fdt/dts/mips/fbsd-mt7620a.dtsi create mode 100644 sys/boot/fdt/dts/mips/fbsd-mt7620n.dtsi create mode 100644 sys/boot/fdt/dts/mips/fbsd-mt7621.dtsi create mode 100644 sys/boot/fdt/dts/mips/fbsd-mt7628an.dtsi create mode 100644 sys/boot/fdt/dts/mips/fbsd-rt2880.dtsi create mode 100644 sys/boot/fdt/dts/mips/fbsd-rt3050.dtsi create mode 100644 sys/boot/fdt/dts/mips/fbsd-rt3352.dtsi create mode 100644 sys/boot/fdt/dts/mips/fbsd-rt3883.dtsi create mode 100644 sys/boot/fdt/dts/mips/fbsd-rt5350.dtsi diff --git a/sys/boot/fdt/dts/mips/fbsd-mt7620a.dtsi b/sys/boot/fdt/dts/mips/fbsd-mt7620a.dtsi new file mode 100644 index 000000000000..8f4c9d56dcc8 --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-mt7620a.dtsi @@ -0,0 +1,52 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + palmbus@10000000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uartlite@c00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uartlite@c00 {}; + }; + + usbphy: usbphy { + clocks = <&clkctrl 22 &clkctrl 25>; + clock-names = "host", "device"; + }; + + pcie@10140000 { + /* + * Our driver is different that OpenWRT's, so we need slightly + * different values for the reg property + */ + reg = <0x10140000 0x10000>; + + /* + * Also, we need resets and clocks defined, so we can properly + * initialize the PCIe + */ + clocks = <&clkctrl 26>; + }; +}; diff --git a/sys/boot/fdt/dts/mips/fbsd-mt7620n.dtsi b/sys/boot/fdt/dts/mips/fbsd-mt7620n.dtsi new file mode 100644 index 000000000000..c1d537b5d993 --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-mt7620n.dtsi @@ -0,0 +1,38 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + palmbus@10000000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uartlite@c00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uartlite@c00 {}; + }; + + usbphy: usbphy { + clocks = <&clkctrl 22 &clkctrl 25>; + clock-names = "host", "device"; + }; +}; diff --git a/sys/boot/fdt/dts/mips/fbsd-mt7621.dtsi b/sys/boot/fdt/dts/mips/fbsd-mt7621.dtsi new file mode 100644 index 000000000000..91ae1b12fbf8 --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-mt7621.dtsi @@ -0,0 +1,102 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + gic: interrupt-controller@1fbc0000 { + /* + * OpenWRT does not define the GIC interrupt, but we need it + * for now, at least until we re-work our GIC driver + */ + interrupt-parent = <&cpuintc>; + interrupts = <2>; + }; + + palmbus@1E000000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uartlite@c00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uartlite@c00 { + /* + * Mark uartlite as compatible to mtk,ns16550a instead + * of simply ns16550a so we can autodetect the UART + * clock + */ + compatible = "mtk,ns16550a"; + }; + + gpio@600 { + /* + * Mark gpio as compatible to simple-bus and override + * its #size-cells and provide a default ranges property + * so we can attach instances of our mtk_gpio_v2 driver + * to it for now. Provide exactly the same resources to + * the instances of mtk_gpio_v2. + */ + compatible = "simple-bus"; + ranges = <0x0 0x600 0x100>; + #size-cells = <1>; + + interrupt-parent = <&gic>; + + gpio0: bank@0 { + reg = <0x0 0x100>; + interrupts = ; + }; + + gpio1: bank@1 { + reg = <0x0 0x100>; + interrupts = ; + }; + + gpio2: bank@2 { + reg = <0x0 0x100>; + interrupts = ; + }; + }; + }; + + xhci@1E1C0000 { + /* + * A slightly different value for reg size is needed by our + * driver for the moment + */ + reg = <0x1e1c0000 0x20000>; + }; + + pcie@1e140000 { + /* + * Our driver is different that OpenWRT's, so we need slightly + * different values for the reg property + */ + reg = <0x1e140000 0x10000>; + + /* + * Also, we need resets and clocks defined, so we can properly + * initialize the PCIe + */ + resets = <&rstctrl 24>, <&rstctrl 25>, <&rstctrl 26>; + clocks = <&clkctrl 24>, <&clkctrl 25>, <&clkctrl 26>; + }; +}; diff --git a/sys/boot/fdt/dts/mips/fbsd-mt7628an.dtsi b/sys/boot/fdt/dts/mips/fbsd-mt7628an.dtsi new file mode 100644 index 000000000000..42401b57d1c2 --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-mt7628an.dtsi @@ -0,0 +1,88 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + palmbus@10000000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uart2@e00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uart2@e00 { + /* + * Mark uartlite as compatible to mtk,ns16550a instead + * of simply ns16550a so we can autodetect the UART + * clock + */ + compatible = "mtk,ns16550a"; + }; + + gpio@600 { + /* + * Mark gpio as compatible to simple-bus and override + * its #size-cells and provide a default ranges property + * so we can attach instances of our mtk_gpio_v2 driver + * to it for now. Provide exactly the same resources to + * the instances of mtk_gpio_v2. + */ + compatible = "simple-bus"; + ranges = <0x0 0x600 0x100>; + #size-cells = <1>; + + gpio0: bank@0 { + reg = <0x0 0x100>; + interrupts = <6>; + }; + + gpio1: bank@1 { + reg = <0x0 0x100>; + interrupts = <6>; + }; + + gpio2: bank@2 { + reg = <0x0 0x100>; + interrupts = <6>; + }; + }; + }; + + usbphy: usbphy@10120000 { + clocks = <&clkctrl 22 &clkctrl 25>; + clock-names = "host", "device"; + }; + + pcie@10140000 { + /* + * Our driver is different that OpenWRT's, so we need slightly + * different values for the reg property + */ + reg = <0x10140000 0x10000>; + + /* + * Also, we need resets and clocks defined, so we can properly + * initialize the PCIe + */ + resets = <&rstctrl 26>, <&rstctrl 27>; + clocks = <&clkctrl 26>, <&clkctrl 27>; + }; +}; diff --git a/sys/boot/fdt/dts/mips/fbsd-rt2880.dtsi b/sys/boot/fdt/dts/mips/fbsd-rt2880.dtsi new file mode 100644 index 000000000000..96ebafea5b52 --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-rt2880.dtsi @@ -0,0 +1,33 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + palmbus@300000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uartlite@c00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uartlite@c00 {}; + }; +}; diff --git a/sys/boot/fdt/dts/mips/fbsd-rt3050.dtsi b/sys/boot/fdt/dts/mips/fbsd-rt3050.dtsi new file mode 100644 index 000000000000..13eb530fee5e --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-rt3050.dtsi @@ -0,0 +1,41 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + palmbus@10000000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uartlite@c00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uartlite@c00 {}; + }; + + usbphy: usbphy { + compatible = "ralink,rt3050-usbphy"; + resets = <&rstctrl 22>; + reset-names = "otg"; + clocks = <&clkctrl 18>; + clock-names = "otg"; + }; +}; diff --git a/sys/boot/fdt/dts/mips/fbsd-rt3352.dtsi b/sys/boot/fdt/dts/mips/fbsd-rt3352.dtsi new file mode 100644 index 000000000000..a6a688733d20 --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-rt3352.dtsi @@ -0,0 +1,38 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + palmbus@10000000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uartlite@c00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uartlite@c00 {}; + }; + + usbphy { + clocks = <&clkctrl 18 &clkctrl 20>; + clock-names = "host", "device"; + }; +}; diff --git a/sys/boot/fdt/dts/mips/fbsd-rt3883.dtsi b/sys/boot/fdt/dts/mips/fbsd-rt3883.dtsi new file mode 100644 index 000000000000..de32f9ba16cc --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-rt3883.dtsi @@ -0,0 +1,50 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + palmbus@10000000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uartlite@c00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uartlite@c00 {}; + }; + + usbphy: usbphy { + clocks = <&clkctrl 22 &clkctrl 25>; + clock-names = "host", "device"; + }; + + pci@10140000 { + #address-cells = <3>; + #size-cells = <2>; + ranges = < + 0x02000000 0 0x00000000 0x20000000 0 0x10000000 + 0x01000000 0 0x00000000 0x10160000 0 0x00010000 + >; + + interrupt-parent = <&cpuintc>; + interrupts = <4>; + }; +}; diff --git a/sys/boot/fdt/dts/mips/fbsd-rt5350.dtsi b/sys/boot/fdt/dts/mips/fbsd-rt5350.dtsi new file mode 100644 index 000000000000..5cc5383d7bc5 --- /dev/null +++ b/sys/boot/fdt/dts/mips/fbsd-rt5350.dtsi @@ -0,0 +1,38 @@ +/* $FreeBSD$ */ + +/ { + + /* + * FreeBSD's stdin and stdout, so we can have a console + */ + chosen { + stdin = &uartlite; + stdout = &uartlite; + }; + + /* + * OpenWRT doesn't define a clock controller, but we currently need one + */ + clkctrl: cltctrl { + compatible = "ralink,rt2880-clock"; + #clock-cells = <1>; + }; + + palmbus@10000000 { + /* + * Make palmbus compatible to our simplebus + */ + compatible = "simple-bus"; + + /* + * Reference uartlite@c00 as uartlite, so we can address it + * within the chosen node above + */ + uartlite: uartlite@c00 {}; + }; + + usbphy { + clocks = <&clkctrl 18>; + clock-names = "host"; + }; +}; From 4fde2bf0a5c2be74f596489a57fd30c9810b1c4d Mon Sep 17 00:00:00 2001 From: Phil Shafer Date: Fri, 15 Apr 2016 15:42:12 +0000 Subject: [PATCH 122/143] Import libxo 0.4.7 --- configure.ac | 2 +- doc/libxo-manual.html | 4 +- libxo/libxo.c | 18 +-- libxo/xo_config.h.in | 246 ------------------------------ libxo/xo_format.5 | 2 +- tests/core/saved/test_01.E.out | 10 ++ tests/core/saved/test_01.H.out | 2 +- tests/core/saved/test_01.HIPx.out | 19 +++ tests/core/saved/test_01.HP.out | 19 +++ tests/core/saved/test_01.J.out | 2 +- tests/core/saved/test_01.JP.out | 12 +- tests/core/saved/test_01.T.out | 2 + tests/core/saved/test_01.X.out | 2 +- tests/core/saved/test_01.XP.out | 10 ++ tests/core/test_01.c | 10 ++ 15 files changed, 97 insertions(+), 263 deletions(-) delete mode 100644 libxo/xo_config.h.in diff --git a/configure.ac b/configure.ac index e7bc61dfc127..1d86f0e5030c 100644 --- a/configure.ac +++ b/configure.ac @@ -12,7 +12,7 @@ # AC_PREREQ(2.2) -AC_INIT([libxo], [0.4.6], [phil@juniper.net]) +AC_INIT([libxo], [0.4.7], [phil@juniper.net]) AM_INIT_AUTOMAKE([-Wall -Werror foreign -Wno-portability]) # Support silent build rules. Requires at least automake-1.11. diff --git a/doc/libxo-manual.html b/doc/libxo-manual.html index bc4463d363b9..47881da91ab5 100644 --- a/doc/libxo-manual.html +++ b/doc/libxo-manual.html @@ -515,7 +515,7 @@ li.indline1 { } @top-right { - content: "August 2015"; + content: "December 2015"; } @top-center { @@ -22009,7 +22009,7 @@ jQuery(function ($) { -August 24, 2015 +December 30, 2015

libxo: The Easy Way to Generate text, XML, JSON, and HTML output
libxo-manual

diff --git a/libxo/libxo.c b/libxo/libxo.c index cceebfa3a3d7..bae810f179c7 100644 --- a/libxo/libxo.c +++ b/libxo/libxo.c @@ -3374,6 +3374,15 @@ xo_buf_append_div (xo_handle_t *xop, const char *class, xo_xff_flags_t flags, static char div_end[] = "\">"; static char div_close[] = ""; + /* The encoding format defaults to the normal format */ + if (encoding == NULL) { + char *enc = alloca(vlen + 1); + memcpy(enc, value, vlen); + enc[vlen] = '\0'; + encoding = xo_fix_encoding(xop, enc); + elen = strlen(encoding); + } + /* * To build our XPath predicate, we need to save the va_list before * we format our data, and then restore it before we format the @@ -3406,15 +3415,6 @@ xo_buf_append_div (xo_handle_t *xop, const char *class, xo_xff_flags_t flags, else xo_buf_append(pbp, "='", 2); - /* The encoding format defaults to the normal format */ - if (encoding == NULL) { - char *enc = alloca(vlen + 1); - memcpy(enc, value, vlen); - enc[vlen] = '\0'; - encoding = xo_fix_encoding(xop, enc); - elen = strlen(encoding); - } - xo_xff_flags_t pflags = flags | XFF_XML | XFF_ATTR; pflags &= ~(XFF_NO_OUTPUT | XFF_ENCODE_ONLY); xo_do_format_field(xop, pbp, encoding, elen, pflags); diff --git a/libxo/xo_config.h.in b/libxo/xo_config.h.in deleted file mode 100644 index 614e7fec728a..000000000000 --- a/libxo/xo_config.h.in +++ /dev/null @@ -1,246 +0,0 @@ -/* libxo/xo_config.h.in. Generated from configure.ac by autoheader. */ - -/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP - systems. This function is required for `alloca.c' support on those systems. - */ -#undef CRAY_STACKSEG_END - -/* Define to 1 if using `alloca.c'. */ -#undef C_ALLOCA - -/* Define to 1 if you have `alloca', as a function or macro. */ -#undef HAVE_ALLOCA - -/* Define to 1 if you have and it should be used (not on Ultrix). - */ -#undef HAVE_ALLOCA_H - -/* Define to 1 if you have the `asprintf' function. */ -#undef HAVE_ASPRINTF - -/* Define to 1 if you have the `bzero' function. */ -#undef HAVE_BZERO - -/* Define to 1 if you have the `ctime' function. */ -#undef HAVE_CTIME - -/* Define to 1 if you have the header file. */ -#undef HAVE_CTYPE_H - -/* Define to 1 if you have the declaration of `__isthreaded', and to 0 if you - don't. */ -#undef HAVE_DECL___ISTHREADED - -/* Define to 1 if you have the header file. */ -#undef HAVE_DLFCN_H - -/* Define to 1 if you have the `dlfunc' function. */ -#undef HAVE_DLFUNC - -/* Define to 1 if you have the header file. */ -#undef HAVE_ERRNO_H - -/* Define to 1 if you have the `fdopen' function. */ -#undef HAVE_FDOPEN - -/* Define to 1 if you have the `flock' function. */ -#undef HAVE_FLOCK - -/* Define to 1 if you have the `getpass' function. */ -#undef HAVE_GETPASS - -/* Define to 1 if you have the `getprogname' function. */ -#undef HAVE_GETPROGNAME - -/* Define to 1 if you have the `getrusage' function. */ -#undef HAVE_GETRUSAGE - -/* gettext(3) */ -#undef HAVE_GETTEXT - -/* Define to 1 if you have the `gettimeofday' function. */ -#undef HAVE_GETTIMEOFDAY - -/* humanize_number(3) */ -#undef HAVE_HUMANIZE_NUMBER - -/* Define to 1 if you have the header file. */ -#undef HAVE_INTTYPES_H - -/* Define to 1 if you have the `crypto' library (-lcrypto). */ -#undef HAVE_LIBCRYPTO - -/* Define to 1 if you have the `m' library (-lm). */ -#undef HAVE_LIBM - -/* Define to 1 if you have the header file. */ -#undef HAVE_LIBUTIL_H - -/* Define to 1 if your system has a GNU libc compatible `malloc' function, and - to 0 otherwise. */ -#undef HAVE_MALLOC - -/* Define to 1 if you have the `memmove' function. */ -#undef HAVE_MEMMOVE - -/* Define to 1 if you have the header file. */ -#undef HAVE_MEMORY_H - -/* Support printflike */ -#undef HAVE_PRINTFLIKE - -/* Define to 1 if your system has a GNU libc compatible `realloc' function, - and to 0 otherwise. */ -#undef HAVE_REALLOC - -/* Define to 1 if you have the `srand' function. */ -#undef HAVE_SRAND - -/* Define to 1 if you have the `sranddev' function. */ -#undef HAVE_SRANDDEV - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDINT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDIO_EXT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDIO_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDLIB_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STDTIME_TZFILE_H - -/* Define to 1 if you have the `strchr' function. */ -#undef HAVE_STRCHR - -/* Define to 1 if you have the `strcspn' function. */ -#undef HAVE_STRCSPN - -/* Define to 1 if you have the `strerror' function. */ -#undef HAVE_STRERROR - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRINGS_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_STRING_H - -/* Define to 1 if you have the `strlcpy' function. */ -#undef HAVE_STRLCPY - -/* Define to 1 if you have the `strspn' function. */ -#undef HAVE_STRSPN - -/* Have struct sockaddr_un.sun_len */ -#undef HAVE_SUN_LEN - -/* Define to 1 if you have the `sysctlbyname' function. */ -#undef HAVE_SYSCTLBYNAME - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_PARAM_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_STAT_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_SYSCTL_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_TIME_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_SYS_TYPES_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_THREADS_H - -/* thread-local setting */ -#undef HAVE_THREAD_LOCAL - -/* Define to 1 if you have the header file. */ -#undef HAVE_TZFILE_H - -/* Define to 1 if you have the header file. */ -#undef HAVE_UNISTD_H - -/* Define to 1 if you have the `__flbf' function. */ -#undef HAVE___FLBF - -/* Enable debugging */ -#undef LIBXO_DEBUG - -/* Enable text-only rendering */ -#undef LIBXO_TEXT_ONLY - -/* Version number as dotted value */ -#undef LIBXO_VERSION - -/* Version number extra information */ -#undef LIBXO_VERSION_EXTRA - -/* Version number as a number */ -#undef LIBXO_VERSION_NUMBER - -/* Version number as string */ -#undef LIBXO_VERSION_STRING - -/* Enable local wcwidth implementation */ -#undef LIBXO_WCWIDTH - -/* Define to the sub-directory where libtool stores uninstalled libraries. */ -#undef LT_OBJDIR - -/* Name of package */ -#undef PACKAGE - -/* Define to the address where bug reports for this package should be sent. */ -#undef PACKAGE_BUGREPORT - -/* Define to the full name of this package. */ -#undef PACKAGE_NAME - -/* Define to the full name and version of this package. */ -#undef PACKAGE_STRING - -/* Define to the one symbol short name of this package. */ -#undef PACKAGE_TARNAME - -/* Define to the home page for this package. */ -#undef PACKAGE_URL - -/* Define to the version of this package. */ -#undef PACKAGE_VERSION - -/* If using the C implementation of alloca, define if you know the - direction of stack growth for your system; otherwise it will be - automatically deduced at runtime. - STACK_DIRECTION > 0 => grows toward higher addresses - STACK_DIRECTION < 0 => grows toward lower addresses - STACK_DIRECTION = 0 => direction of growth unknown */ -#undef STACK_DIRECTION - -/* Define to 1 if you have the ANSI C header files. */ -#undef STDC_HEADERS - -/* Version number of package */ -#undef VERSION - -/* Define to `__inline__' or `__inline' if that's what the C compiler - calls it, or to nothing if 'inline' is not supported under any name. */ -#ifndef __cplusplus -#undef inline -#endif - -/* Define to rpl_malloc if the replacement function should be used. */ -#undef malloc - -/* Define to rpl_realloc if the replacement function should be used. */ -#undef realloc - -/* Define to `unsigned int' if does not define. */ -#undef size_t diff --git a/libxo/xo_format.5 b/libxo/xo_format.5 index 1db4fc8dc118..8c3cbea31248 100644 --- a/libxo/xo_format.5 +++ b/libxo/xo_format.5 @@ -367,7 +367,7 @@ particular output styles: .It l "leaf-list " "Field is a leaf-list, a list of leaf values" .It n "no-quotes " "Do not quote the field when using JSON style" .It q "quotes " "Quote the field when using JSON style" -.It q "trim " "Trim leading and trailing whitespace" +.It t "trim " "Trim leading and trailing whitespace" .It w "white space " "A blank ("" "") is appended after the label" .El .Pp diff --git a/tests/core/saved/test_01.E.out b/tests/core/saved/test_01.E.out index 296a34ef996a..ed615a5aab84 100644 --- a/tests/core/saved/test_01.E.out +++ b/tests/core/saved/test_01.E.out @@ -114,6 +114,16 @@ op close_list: [item] [] op close_container: [data4] [] op content: [cost] [425] op content: [cost] [455] +op string: [mode] [mode] +op string: [mode_octal] [octal] +op string: [links] [links] +op string: [user] [user] +op string: [group] [group] +op string: [mode] [/some/file] +op content: [mode_octal] [640] +op content: [links] [1] +op string: [user] [user] +op string: [group] [group] op close_container: [top] [] op finish: [] [] op flush: [] [] diff --git a/tests/core/saved/test_01.H.out b/tests/core/saved/test_01.H.out index ead320e0e610..39d8bd4e8a6f 100644 --- a/tests/core/saved/test_01.H.out +++ b/tests/core/saved/test_01.H.out @@ -1 +1 @@ -
Connecting to
my-box
.
example.com
...
Item
Total Sold
In Stock
On Order
SKU
gum
1412
54
10
GRO-000-415
rope
85
4
2
HRD-000-212
ladder
0
2
1
HRD-000-517
bolt
4123
144
42
HRD-000-632
water
17
14
2
GRO-000-2331
Item
'
gum
':
Total sold
:
1412.0
In stock
:
54
On order
:
10
SKU
:
GRO-000-415
Item
'
rope
':
Total sold
:
85.0
In stock
:
4
On order
:
2
SKU
:
HRD-000-212
Item
'
ladder
':
Total sold
:
0
In stock
:
2
On order
:
1
SKU
:
HRD-000-517
Item
'
bolt
':
Total sold
:
4123.0
In stock
:
144
On order
:
42
SKU
:
HRD-000-632
Item
'
water
':
Total sold
:
17.0
In stock
:
14
On order
:
2
SKU
:
GRO-000-2331
Item
'
fish
':
Total sold
:
1321.0
In stock
:
45
On order
:
1
SKU
:
GRO-000-533
Item
:
gum
Item
:
rope
Item
:
ladder
Item
:
bolt
Item
:
water
X
X
X
X
X
X
X
X
X
X
Cost
:
425
X
X
Cost
:
455
\ No newline at end of file +
Connecting to
my-box
.
example.com
...
Item
Total Sold
In Stock
On Order
SKU
gum
1412
54
10
GRO-000-415
rope
85
4
2
HRD-000-212
ladder
0
2
1
HRD-000-517
bolt
4123
144
42
HRD-000-632
water
17
14
2
GRO-000-2331
Item
'
gum
':
Total sold
:
1412.0
In stock
:
54
On order
:
10
SKU
:
GRO-000-415
Item
'
rope
':
Total sold
:
85.0
In stock
:
4
On order
:
2
SKU
:
HRD-000-212
Item
'
ladder
':
Total sold
:
0
In stock
:
2
On order
:
1
SKU
:
HRD-000-517
Item
'
bolt
':
Total sold
:
4123.0
In stock
:
144
On order
:
42
SKU
:
HRD-000-632
Item
'
water
':
Total sold
:
17.0
In stock
:
14
On order
:
2
SKU
:
GRO-000-2331
Item
'
fish
':
Total sold
:
1321.0
In stock
:
45
On order
:
1
SKU
:
GRO-000-533
Item
:
gum
Item
:
rope
Item
:
ladder
Item
:
bolt
Item
:
water
X
X
X
X
X
X
X
X
X
X
Cost
:
425
X
X
Cost
:
455
links
user
group
/some/file
1
user
group
\ No newline at end of file diff --git a/tests/core/saved/test_01.HIPx.out b/tests/core/saved/test_01.HIPx.out index 2b8e2969a062..a3aa369310f1 100644 --- a/tests/core/saved/test_01.HIPx.out +++ b/tests/core/saved/test_01.HIPx.out @@ -301,3 +301,22 @@
455
+
+
+
links
+
+
user
+
+
group
+
+
+
+
/some/file
+
+
1
+
+
user
+
+
group
+
+
diff --git a/tests/core/saved/test_01.HP.out b/tests/core/saved/test_01.HP.out index c8f2dbcb329f..c877dfd01928 100644 --- a/tests/core/saved/test_01.HP.out +++ b/tests/core/saved/test_01.HP.out @@ -301,3 +301,22 @@
455
+
+
+
links
+
+
user
+
+
group
+
+
+
+
/some/file
+
+
1
+
+
user
+
+
group
+
+
diff --git a/tests/core/saved/test_01.J.out b/tests/core/saved/test_01.J.out index 69e3faa62126..0515a2a6e615 100644 --- a/tests/core/saved/test_01.J.out +++ b/tests/core/saved/test_01.J.out @@ -1,2 +1,2 @@ -{"top": {"host":"my-box","domain":"example.com", "data": {"item": [{"sku":"GRO-000-415","name":"gum","sold":1412,"in-stock":54,"on-order":10}, {"sku":"HRD-000-212","name":"rope","sold":85,"in-stock":4,"on-order":2}, {"sku":"HRD-000-517","name":"ladder","sold":0,"in-stock":2,"on-order":1}, {"sku":"HRD-000-632","name":"bolt","sold":4123,"in-stock":144,"on-order":42}, {"sku":"GRO-000-2331","name":"water","sold":17,"in-stock":14,"on-order":2}]}, "data2": {"item": [{"sku":"GRO-000-415","name":"gum","sold":1412.0,"in-stock":54,"on-order":10}, {"sku":"HRD-000-212","name":"rope","sold":85.0,"in-stock":4,"on-order":2}, {"sku":"HRD-000-517","name":"ladder","sold":0,"in-stock":2,"on-order":1}, {"sku":"HRD-000-632","name":"bolt","sold":4123.0,"in-stock":144,"on-order":42}, {"sku":"GRO-000-2331","name":"water","sold":17.0,"in-stock":14,"on-order":2}]}, "data3": {"item": [{"sku":"GRO-000-533","name":"fish","sold":1321.0,"in-stock":45,"on-order":1}]}, "data4": {"item": ["gum","rope","ladder","bolt","water"]},"cost":425,"cost":455} +{"top": {"host":"my-box","domain":"example.com", "data": {"item": [{"sku":"GRO-000-415","name":"gum","sold":1412,"in-stock":54,"on-order":10}, {"sku":"HRD-000-212","name":"rope","sold":85,"in-stock":4,"on-order":2}, {"sku":"HRD-000-517","name":"ladder","sold":0,"in-stock":2,"on-order":1}, {"sku":"HRD-000-632","name":"bolt","sold":4123,"in-stock":144,"on-order":42}, {"sku":"GRO-000-2331","name":"water","sold":17,"in-stock":14,"on-order":2}]}, "data2": {"item": [{"sku":"GRO-000-415","name":"gum","sold":1412.0,"in-stock":54,"on-order":10}, {"sku":"HRD-000-212","name":"rope","sold":85.0,"in-stock":4,"on-order":2}, {"sku":"HRD-000-517","name":"ladder","sold":0,"in-stock":2,"on-order":1}, {"sku":"HRD-000-632","name":"bolt","sold":4123.0,"in-stock":144,"on-order":42}, {"sku":"GRO-000-2331","name":"water","sold":17.0,"in-stock":14,"on-order":2}]}, "data3": {"item": [{"sku":"GRO-000-533","name":"fish","sold":1321.0,"in-stock":45,"on-order":1}]}, "data4": {"item": ["gum","rope","ladder","bolt","water"]},"cost":425,"cost":455,"mode":"mode","mode_octal":"octal","links":"links","user":"user","group":"group","mode":"/some/file","mode_octal":640,"links":1,"user":"user","group":"group"} } diff --git a/tests/core/saved/test_01.JP.out b/tests/core/saved/test_01.JP.out index e65897fe7244..210266d87f77 100644 --- a/tests/core/saved/test_01.JP.out +++ b/tests/core/saved/test_01.JP.out @@ -101,6 +101,16 @@ ] }, "cost": 425, - "cost": 455 + "cost": 455, + "mode": "mode", + "mode_octal": "octal", + "links": "links", + "user": "user", + "group": "group", + "mode": "/some/file", + "mode_octal": 640, + "links": 1, + "user": "user", + "group": "group" } } diff --git a/tests/core/saved/test_01.T.out b/tests/core/saved/test_01.T.out index 2ecf537dd21b..cdf704b880ad 100644 --- a/tests/core/saved/test_01.T.out +++ b/tests/core/saved/test_01.T.out @@ -45,3 +45,5 @@ Item: water XXXXXXXX X XCost: 425 X XCost: 455 + links user group +/some/file 1 user group diff --git a/tests/core/saved/test_01.X.out b/tests/core/saved/test_01.X.out index 46f501e24724..bc9ef84f63ec 100644 --- a/tests/core/saved/test_01.X.out +++ b/tests/core/saved/test_01.X.out @@ -1 +1 @@ -my-boxexample.comGRO-000-415gum14125410HRD-000-212rope8542HRD-000-517ladder021HRD-000-632bolt412314442GRO-000-2331water17142GRO-000-415gum1412.05410HRD-000-212rope85.042HRD-000-517ladder021HRD-000-632bolt4123.014442GRO-000-2331water17.0142GRO-000-533fish1321.0451gumropeladderboltwater425455 \ No newline at end of file +my-boxexample.comGRO-000-415gum14125410HRD-000-212rope8542HRD-000-517ladder021HRD-000-632bolt412314442GRO-000-2331water17142GRO-000-415gum1412.05410HRD-000-212rope85.042HRD-000-517ladder021HRD-000-632bolt4123.014442GRO-000-2331water17.0142GRO-000-533fish1321.0451gumropeladderboltwater425455modeoctallinksusergroup/some/file6401usergroup \ No newline at end of file diff --git a/tests/core/saved/test_01.XP.out b/tests/core/saved/test_01.XP.out index c7f4bfe8d98b..f7d7e5c9246f 100644 --- a/tests/core/saved/test_01.XP.out +++ b/tests/core/saved/test_01.XP.out @@ -93,4 +93,14 @@ 425 455 + mode + octal + links + user + group + /some/file + 640 + 1 + user + group diff --git a/tests/core/test_01.c b/tests/core/test_01.c index f7fe61ec1ebe..5c748772fb9f 100644 --- a/tests/core/test_01.c +++ b/tests/core/test_01.c @@ -169,6 +169,16 @@ main (int argc, char **argv) xo_emit("X{P: }X{Lwc:Cost}{:cost/%u}\n", 425); xo_emit("X{P:/%30s}X{Lwc:Cost}{:cost/%u}\n", "", 455); + xo_emit("{e:mode/%s}{e:mode_octal/%s} {t:links/%s} " + "{t:user/%s} {t:group/%s} \n", + "mode", "octal", "links", + "user", "group", "extra1", "extra2", "extra3"); + + xo_emit("{t:mode/%s}{e:mode_octal/%03o} {t:links/%*u} " + "{t:user/%-*s} {t:group/%-*s} \n", + "/some/file", (int) 0640, 8, 1, + 10, "user", 12, "group"); + xo_close_container_h(NULL, "top"); xo_finish(); From 915c6043b06c1ef2afd4660e18a18d0ed434333d Mon Sep 17 00:00:00 2001 From: Stanislav Galabov Date: Fri, 15 Apr 2016 15:44:02 +0000 Subject: [PATCH 123/143] Make NIRQ configurable for MIPS Submitted by: kan Reviewed by: kan Approved by: adrian (mentor) Differential Revision: https://reviews.freebsd.org/D5964 --- sys/conf/options.mips | 1 + sys/mips/include/intr.h | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/sys/conf/options.mips b/sys/conf/options.mips index 69708ccafea0..10e2c1b24846 100644 --- a/sys/conf/options.mips +++ b/sys/conf/options.mips @@ -145,3 +145,4 @@ PV_STATS opt_pmap.h # Options to use INTRNG code # MIPS_INTRNG opt_global.h +MIPS_NIRQ opt_global.h diff --git a/sys/mips/include/intr.h b/sys/mips/include/intr.h index 28f798f42214..e7258fe3078f 100644 --- a/sys/mips/include/intr.h +++ b/sys/mips/include/intr.h @@ -47,8 +47,12 @@ #include -#ifndef NIRQ -#define NIRQ 128 +#ifndef MIPS_NIRQ +#define MIPS_NIRQ 128 +#endif + +#ifndef NIRQ +#define NIRQ MIPS_NIRQ #endif #define INTR_IRQ_NSPC_SWI 4 From 99d628d577710a8236fd8cfca76bad9eb43b22c8 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 15:46:41 +0000 Subject: [PATCH 124/143] netinet: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. Reviewed by: ae. tuexen --- sys/netinet/if_ether.c | 2 +- sys/netinet/igmp.c | 2 +- sys/netinet/in_mcast.c | 4 ++-- sys/netinet/ip_divert.c | 6 +++--- sys/netinet/ip_icmp.c | 4 ++-- sys/netinet/ip_mroute.c | 2 +- sys/netinet/ip_options.c | 2 +- sys/netinet/ip_output.c | 2 +- sys/netinet/libalias/alias_db.c | 6 +++--- sys/netinet/raw_ip.c | 2 +- sys/netinet/sctp_syscalls.c | 2 +- sys/netinet/sctp_usrreq.c | 2 +- sys/netinet/udp_usrreq.c | 4 ++-- 13 files changed, 20 insertions(+), 20 deletions(-) diff --git a/sys/netinet/if_ether.c b/sys/netinet/if_ether.c index 7a06beaf7cc0..eac3c1d24782 100644 --- a/sys/netinet/if_ether.c +++ b/sys/netinet/if_ether.c @@ -578,7 +578,7 @@ int arpresolve(struct ifnet *ifp, int is_gw, struct mbuf *m, const struct sockaddr *dst, u_char *desten, uint32_t *pflags) { - struct llentry *la = 0; + struct llentry *la = NULL; if (pflags != NULL) *pflags = 0; diff --git a/sys/netinet/igmp.c b/sys/netinet/igmp.c index 2154149bc7b0..dcadec559e68 100644 --- a/sys/netinet/igmp.c +++ b/sys/netinet/igmp.c @@ -1469,7 +1469,7 @@ igmp_input(struct mbuf **mp, int *offp, int proto) else minlen += IGMP_MINLEN; if ((!M_WRITABLE(m) || m->m_len < minlen) && - (m = m_pullup(m, minlen)) == 0) { + (m = m_pullup(m, minlen)) == NULL) { IGMPSTAT_INC(igps_rcv_tooshort); return (IPPROTO_DONE); } diff --git a/sys/netinet/in_mcast.c b/sys/netinet/in_mcast.c index f2a985b79ef5..4037dbfbff4d 100644 --- a/sys/netinet/in_mcast.c +++ b/sys/netinet/in_mcast.c @@ -1810,7 +1810,7 @@ inp_getmoptions(struct inpcb *inp, struct sockopt *sopt) break; case IP_MULTICAST_TTL: - if (imo == 0) + if (imo == NULL) optval = coptval = IP_DEFAULT_MULTICAST_TTL; else optval = coptval = imo->imo_multicast_ttl; @@ -1822,7 +1822,7 @@ inp_getmoptions(struct inpcb *inp, struct sockopt *sopt) break; case IP_MULTICAST_LOOP: - if (imo == 0) + if (imo == NULL) optval = coptval = IP_DEFAULT_MULTICAST_LOOP; else optval = coptval = imo->imo_multicast_loop; diff --git a/sys/netinet/ip_divert.c b/sys/netinet/ip_divert.c index f23a3a87fe23..233d1af7cda9 100644 --- a/sys/netinet/ip_divert.c +++ b/sys/netinet/ip_divert.c @@ -205,7 +205,7 @@ divert_packet(struct mbuf *m, int incoming) } /* Assure header */ if (m->m_len < sizeof(struct ip) && - (m = m_pullup(m, sizeof(struct ip))) == 0) + (m = m_pullup(m, sizeof(struct ip))) == NULL) return; ip = mtod(m, struct ip *); @@ -600,7 +600,7 @@ div_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam, /* Packet must have a header (but that's about it) */ if (m->m_len < sizeof (struct ip) && - (m = m_pullup(m, sizeof (struct ip))) == 0) { + (m = m_pullup(m, sizeof (struct ip))) == NULL) { KMOD_IPSTAT_INC(ips_toosmall); m_freem(m); return EINVAL; @@ -666,7 +666,7 @@ div_pcblist(SYSCTL_HANDLER_ARGS) return error; inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK); - if (inp_list == 0) + if (inp_list == NULL) return ENOMEM; INP_INFO_RLOCK(&V_divcbinfo); diff --git a/sys/netinet/ip_icmp.c b/sys/netinet/ip_icmp.c index cc3e1f514f93..fee980f4cb5a 100644 --- a/sys/netinet/ip_icmp.c +++ b/sys/netinet/ip_icmp.c @@ -674,7 +674,7 @@ icmp_reflect(struct mbuf *m) struct in_ifaddr *ia; struct in_addr t; struct nhop4_extended nh_ext; - struct mbuf *opts = 0; + struct mbuf *opts = NULL; int optlen = (ip->ip_hl << 2) - sizeof(struct ip); if (IN_MULTICAST(ntohl(ip->ip_src.s_addr)) || @@ -790,7 +790,7 @@ icmp_reflect(struct mbuf *m) * add on any record-route or timestamp options. */ cp = (u_char *) (ip + 1); - if ((opts = ip_srcroute(m)) == 0 && + if ((opts = ip_srcroute(m)) == NULL && (opts = m_gethdr(M_NOWAIT, MT_DATA))) { opts->m_len = sizeof(struct in_addr); mtod(opts, struct in_addr *)->s_addr = 0; diff --git a/sys/netinet/ip_mroute.c b/sys/netinet/ip_mroute.c index 69e12c3cd5b5..ba21edccbb1d 100644 --- a/sys/netinet/ip_mroute.c +++ b/sys/netinet/ip_mroute.c @@ -2601,7 +2601,7 @@ pim_input(struct mbuf **mp, int *offp, int proto) * Get the IP and PIM headers in contiguous memory, and * possibly the PIM REGISTER header. */ - if (m->m_len < minlen && (m = m_pullup(m, minlen)) == 0) { + if (m->m_len < minlen && (m = m_pullup(m, minlen)) == NULL) { CTR1(KTR_IPMF, "%s: m_pullup() failed", __func__); return (IPPROTO_DONE); } diff --git a/sys/netinet/ip_options.c b/sys/netinet/ip_options.c index 5daf653baa8a..b0504234e306 100644 --- a/sys/netinet/ip_options.c +++ b/sys/netinet/ip_options.c @@ -608,7 +608,7 @@ ip_pcbopts(struct inpcb *inp, int optname, struct mbuf *m) /* turn off any old options */ if (*pcbopt) (void)m_free(*pcbopt); - *pcbopt = 0; + *pcbopt = NULL; if (m == NULL || m->m_len == 0) { /* * Only turning off any previous options. diff --git a/sys/netinet/ip_output.c b/sys/netinet/ip_output.c index afdf1a782782..3a8be2747303 100644 --- a/sys/netinet/ip_output.c +++ b/sys/netinet/ip_output.c @@ -1348,7 +1348,7 @@ ip_ctloutput(struct socket *so, struct sockopt *sopt) caddr_t req = NULL; size_t len = 0; - if (m != 0) { + if (m != NULL) { req = mtod(m, caddr_t); len = m->m_len; } diff --git a/sys/netinet/libalias/alias_db.c b/sys/netinet/libalias/alias_db.c index cceccd56e6e5..4f8159ba753a 100644 --- a/sys/netinet/libalias/alias_db.c +++ b/sys/netinet/libalias/alias_db.c @@ -784,9 +784,9 @@ FindNewPortGroup(struct libalias *la, struct alias_link *search_result; for (j = 0; j < port_count; j++) - if (0 != (search_result = FindLinkIn(la, dst_addr, alias_addr, - dst_port, htons(port_sys + j), - link_type, 0))) + if ((search_result = FindLinkIn(la, dst_addr, + alias_addr, dst_port, htons(port_sys + j), + link_type, 0)) != NULL) break; /* Found a good range, return base */ diff --git a/sys/netinet/raw_ip.c b/sys/netinet/raw_ip.c index 9f29444cb712..8de3108c8a98 100644 --- a/sys/netinet/raw_ip.c +++ b/sys/netinet/raw_ip.c @@ -1046,7 +1046,7 @@ rip_pcblist(SYSCTL_HANDLER_ARGS) return (error); inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK); - if (inp_list == 0) + if (inp_list == NULL) return (ENOMEM); INP_INFO_RLOCK(&V_ripcbinfo); diff --git a/sys/netinet/sctp_syscalls.c b/sys/netinet/sctp_syscalls.c index 71e2f722a72e..5c16e8d3555e 100644 --- a/sys/netinet/sctp_syscalls.c +++ b/sys/netinet/sctp_syscalls.c @@ -562,7 +562,7 @@ sys_sctp_generic_recvmsg(td, uap) if (fromlen && uap->from) { len = fromlen; - if (len <= 0 || fromsa == 0) + if (len <= 0 || fromsa == NULL) len = 0; else { len = MIN(len, fromsa->sa_len); diff --git a/sys/netinet/sctp_usrreq.c b/sys/netinet/sctp_usrreq.c index 1b23abca7f10..81d2478294d4 100644 --- a/sys/netinet/sctp_usrreq.c +++ b/sys/netinet/sctp_usrreq.c @@ -469,7 +469,7 @@ sctp_attach(struct socket *so, int proto SCTP_UNUSED, struct thread *p SCTP_UNUS uint32_t vrf_id = SCTP_DEFAULT_VRFID; inp = (struct sctp_inpcb *)so->so_pcb; - if (inp != 0) { + if (inp != NULL) { SCTP_LTRACE_ERR_RET(inp, NULL, NULL, SCTP_FROM_SCTP_USRREQ, EINVAL); return (EINVAL); } diff --git a/sys/netinet/udp_usrreq.c b/sys/netinet/udp_usrreq.c index 56aa56f5da0a..fdc2e76dbcfb 100644 --- a/sys/netinet/udp_usrreq.c +++ b/sys/netinet/udp_usrreq.c @@ -308,7 +308,7 @@ udp_append(struct inpcb *inp, struct ip *ip, struct mbuf *n, int off, { struct sockaddr *append_sa; struct socket *so; - struct mbuf *opts = 0; + struct mbuf *opts = NULL; #ifdef INET6 struct sockaddr_in6 udp_in6; #endif @@ -856,7 +856,7 @@ udp_pcblist(SYSCTL_HANDLER_ARGS) return (error); inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK); - if (inp_list == 0) + if (inp_list == NULL) return (ENOMEM); INP_INFO_RLOCK(&V_udbinfo); From 59c3cb81c1769fdb6c840c971df129b52f4a848d Mon Sep 17 00:00:00 2001 From: Andrew Turner Date: Fri, 15 Apr 2016 16:05:41 +0000 Subject: [PATCH 125/143] Rename ARM_INTRNG and MIPS_INTRNG to INTRNG. This will help with machine independent code that needs to know about INTRNG such as PCI drivers. Obtained from: ABT Systems Ltd Sponsored by: The FreeBSD Foundation --- sys/arm/allwinner/a10_common.c | 4 +-- sys/arm/altera/socfpga/socfpga_common.c | 2 +- sys/arm/amlogic/aml8726/aml8726_machdep.c | 4 +-- sys/arm/annapurna/alpine/common.c | 2 +- sys/arm/arm/gic.c | 42 +++++++++++------------ sys/arm/arm/machdep_intr.c | 4 +-- sys/arm/arm/mp_machdep.c | 18 +++++----- sys/arm/arm/nexus.c | 16 ++++----- sys/arm/at91/at91_common.c | 2 +- sys/arm/broadcom/bcm2835/bcm2835_common.c | 4 +-- sys/arm/broadcom/bcm2835/bcm2835_gpio.c | 20 +++++------ sys/arm/broadcom/bcm2835/bcm2835_intr.c | 20 +++++------ sys/arm/broadcom/bcm2835/bcm2836.c | 4 +-- sys/arm/broadcom/bcm2835/bcm2836.h | 2 +- sys/arm/broadcom/bcm2835/bcm2836_mp.c | 2 +- sys/arm/conf/A20 | 2 +- sys/arm/conf/ALPINE | 2 +- sys/arm/conf/ARMADA38X | 2 +- sys/arm/conf/BEAGLEBONE | 2 +- sys/arm/conf/EXYNOS5.common | 2 +- sys/arm/conf/IMX6 | 2 +- sys/arm/conf/ODROIDC1 | 2 +- sys/arm/conf/PANDABOARD | 2 +- sys/arm/conf/RK3188 | 2 +- sys/arm/conf/RPI-B | 2 +- sys/arm/conf/RPI2 | 2 +- sys/arm/conf/SOCKIT.common | 2 +- sys/arm/conf/VIRT | 2 +- sys/arm/conf/VSATV102 | 2 +- sys/arm/conf/VYBRID | 2 +- sys/arm/conf/ZEDBOARD | 2 +- sys/arm/freescale/imx/imx6_machdep.c | 2 +- sys/arm/freescale/imx/imx_common.c | 4 +-- sys/arm/freescale/imx/imx_gpio.c | 14 ++++---- sys/arm/freescale/vybrid/vf_common.c | 2 +- sys/arm/include/intr.h | 6 ++-- sys/arm/include/smp.h | 4 +-- sys/arm/lpc/lpc_intc.c | 2 +- sys/arm/mv/mpic.c | 20 +++++------ sys/arm/mv/mv_common.c | 2 +- sys/arm/nvidia/tegra124/std.tegra124 | 2 +- sys/arm/qemu/virt_common.c | 2 +- sys/arm/rockchip/rk30xx_common.c | 2 +- sys/arm/samsung/exynos/exynos5_common.c | 2 +- sys/arm/ti/aintc.c | 14 ++++---- sys/arm/ti/ti_common.c | 4 +-- sys/arm/ti/ti_gpio.c | 16 ++++----- sys/arm/ti/ti_gpio.h | 6 ++-- sys/arm/versatile/versatile_common.c | 2 +- sys/arm/xilinx/zy7_machdep.c | 2 +- sys/conf/files.arm | 6 ++-- sys/conf/options.arm | 2 +- sys/conf/options.mips | 2 +- sys/dev/fdt/fdt_common.h | 2 +- sys/mips/include/intr.h | 4 +-- sys/mips/include/smp.h | 2 +- sys/mips/mips/exception.S | 8 ++--- sys/mips/mips/nexus.c | 14 ++++---- sys/mips/mips/tick.c | 6 ++-- 59 files changed, 166 insertions(+), 166 deletions(-) diff --git a/sys/arm/allwinner/a10_common.c b/sys/arm/allwinner/a10_common.c index d20853a0af40..82be0c043ab5 100644 --- a/sys/arm/allwinner/a10_common.c +++ b/sys/arm/allwinner/a10_common.c @@ -42,7 +42,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_aintc_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, @@ -69,4 +69,4 @@ fdt_pic_decode_t fdt_pic_table[] = { NULL }; -#endif /* ARM_INTRNG */ +#endif /* INTRNG */ diff --git a/sys/arm/altera/socfpga/socfpga_common.c b/sys/arm/altera/socfpga/socfpga_common.c index 3615c947af98..740d342f6792 100644 --- a/sys/arm/altera/socfpga/socfpga_common.c +++ b/sys/arm/altera/socfpga/socfpga_common.c @@ -74,7 +74,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_pic_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/amlogic/aml8726/aml8726_machdep.c b/sys/arm/amlogic/aml8726/aml8726_machdep.c index 1ad25b4191e7..50371804503b 100644 --- a/sys/arm/amlogic/aml8726/aml8726_machdep.c +++ b/sys/arm/amlogic/aml8726/aml8726_machdep.c @@ -184,7 +184,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG #ifndef DEV_GIC static int fdt_pic_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, @@ -213,4 +213,4 @@ fdt_pic_decode_t fdt_pic_table[] = { #endif NULL }; -#endif /* ARM_INTRNG */ +#endif /* INTRNG */ diff --git a/sys/arm/annapurna/alpine/common.c b/sys/arm/annapurna/alpine/common.c index 5d45b553e07d..cf905569275d 100644 --- a/sys/arm/annapurna/alpine/common.c +++ b/sys/arm/annapurna/alpine/common.c @@ -136,7 +136,7 @@ cpu_reset(void) while (1) {} } -#ifndef ARM_INTRNG +#ifndef INTRNG static int alpine_pic_decode_fdt(uint32_t iparent, uint32_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/arm/gic.c b/sys/arm/arm/gic.c index 0d201fdf45ef..85d15576571c 100644 --- a/sys/arm/arm/gic.c +++ b/sys/arm/arm/gic.c @@ -50,7 +50,7 @@ __FBSDID("$FreeBSD$"); #include #include #include -#ifdef ARM_INTRNG +#ifdef INTRNG #include #endif #include @@ -62,7 +62,7 @@ __FBSDID("$FreeBSD$"); #include #include -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #endif @@ -116,7 +116,7 @@ __FBSDID("$FreeBSD$"); #define GIC_DEFAULT_ICFGR_INIT 0x00000000 #endif -#ifdef ARM_INTRNG +#ifdef INTRNG struct gic_irqsrc { struct intr_irqsrc gi_isrc; uint32_t gi_irq; @@ -136,7 +136,7 @@ u_int sgi_first_unused = GIC_FIRST_SGI; #endif #endif -#ifdef ARM_INTRNG +#ifdef INTRNG struct arm_gic_range { uint64_t bus; uint64_t host; @@ -151,7 +151,7 @@ struct arm_gic_devinfo { struct arm_gic_softc { device_t gic_dev; -#ifdef ARM_INTRNG +#ifdef INTRNG void * gic_intrhand; struct gic_irqsrc * gic_irqs; #endif @@ -167,7 +167,7 @@ struct arm_gic_softc { uint32_t last_irq[MAXCPU]; #endif -#ifdef ARM_INTRNG +#ifdef INTRNG /* FDT child data */ pcell_t addr_cells; pcell_t size_cells; @@ -176,14 +176,14 @@ struct arm_gic_softc { #endif }; -#ifdef ARM_INTRNG +#ifdef INTRNG #define GIC_INTR_ISRC(sc, irq) (&sc->gic_irqs[irq].gi_isrc) #endif static struct resource_spec arm_gic_spec[] = { { SYS_RES_MEMORY, 0, RF_ACTIVE }, /* Distributor registers */ { SYS_RES_MEMORY, 1, RF_ACTIVE }, /* CPU Interrupt Intf. registers */ -#ifdef ARM_INTRNG +#ifdef INTRNG { SYS_RES_IRQ, 0, RF_ACTIVE | RF_OPTIONAL }, /* Parent interrupt */ #endif { -1, 0 } @@ -204,7 +204,7 @@ static struct arm_gic_softc *gic_sc = NULL; #define gic_d_write_4(_sc, _reg, _val) \ bus_space_write_4((_sc)->gic_d_bst, (_sc)->gic_d_bsh, (_reg), (_val)) -#ifndef ARM_INTRNG +#ifndef INTRNG static int gic_config_irq(int irq, enum intr_trigger trig, enum intr_polarity pol); static void gic_post_filter(void *); @@ -235,7 +235,7 @@ arm_gic_probe(device_t dev) return (BUS_PROBE_DEFAULT); } -#ifdef ARM_INTRNG +#ifdef INTRNG static inline void gic_irq_unmask(struct arm_gic_softc *sc, u_int irq) { @@ -275,7 +275,7 @@ gic_cpu_mask(struct arm_gic_softc *sc) } #ifdef SMP -#ifdef ARM_INTRNG +#ifdef INTRNG static void arm_gic_init_secondary(device_t dev) { @@ -347,10 +347,10 @@ arm_gic_init_secondary(device_t dev) gic_d_write_4(sc, GICD_ISENABLER(29 >> 5), (1UL << (29 & 0x1F))); gic_d_write_4(sc, GICD_ISENABLER(30 >> 5), (1UL << (30 & 0x1F))); } -#endif /* ARM_INTRNG */ +#endif /* INTRNG */ #endif /* SMP */ -#ifndef ARM_INTRNG +#ifndef INTRNG int gic_decode_fdt(phandle_t iparent, pcell_t *intr, int *interrupt, int *trig, int *pol) @@ -411,7 +411,7 @@ gic_decode_fdt(phandle_t iparent, pcell_t *intr, int *interrupt, } #endif -#ifdef ARM_INTRNG +#ifdef INTRNG static inline intptr_t gic_xref(device_t dev) { @@ -570,7 +570,7 @@ arm_gic_attach(device_t dev) struct arm_gic_softc *sc; int i; uint32_t icciidr, mask, nirqs; -#ifdef ARM_INTRNG +#ifdef INTRNG phandle_t pxref; intptr_t xref = gic_xref(dev); #endif @@ -606,7 +606,7 @@ arm_gic_attach(device_t dev) nirqs = gic_d_read_4(sc, GICD_TYPER); nirqs = 32 * ((nirqs & 0x1f) + 1); -#ifdef ARM_INTRNG +#ifdef INTRNG if (arm_gic_register_isrcs(sc, nirqs)) { device_printf(dev, "could not register irqs\n"); goto cleanup; @@ -662,7 +662,7 @@ arm_gic_attach(device_t dev) /* Enable interrupt distribution */ gic_d_write_4(sc, GICD_CTLR, 0x01); -#ifndef ARM_INTRNG +#ifndef INTRNG return (0); #else /* @@ -723,7 +723,7 @@ arm_gic_attach(device_t dev) #endif } -#ifdef ARM_INTRNG +#ifdef INTRNG static struct resource * arm_gic_alloc_resource(device_t bus, device_t child, int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags) @@ -1429,14 +1429,14 @@ pic_ipi_clear(int ipi) arm_gic_ipi_clear(gic_sc->gic_dev, ipi); } #endif -#endif /* ARM_INTRNG */ +#endif /* INTRNG */ static device_method_t arm_gic_methods[] = { /* Device interface */ DEVMETHOD(device_probe, arm_gic_probe), DEVMETHOD(device_attach, arm_gic_attach), -#ifdef ARM_INTRNG +#ifdef INTRNG /* Bus interface */ DEVMETHOD(bus_add_child, bus_generic_add_child), DEVMETHOD(bus_alloc_resource, arm_gic_alloc_resource), @@ -1483,7 +1483,7 @@ EARLY_DRIVER_MODULE(gic, simplebus, arm_gic_driver, arm_gic_devclass, 0, 0, EARLY_DRIVER_MODULE(gic, ofwbus, arm_gic_driver, arm_gic_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE); -#ifdef ARM_INTRNG +#ifdef INTRNG /* * GICv2m support -- the GICv2 MSI/MSI-X controller. */ diff --git a/sys/arm/arm/machdep_intr.c b/sys/arm/arm/machdep_intr.c index 504d26212127..b21dfa16f9fd 100644 --- a/sys/arm/arm/machdep_intr.c +++ b/sys/arm/arm/machdep_intr.c @@ -49,7 +49,7 @@ __FBSDID("$FreeBSD$"); #include #include -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #ifdef SMP @@ -131,7 +131,7 @@ arm_irq_memory_barrier(uintptr_t irq) cpu_l2cache_drain_writebuf(); } -#ifdef ARM_INTRNG +#ifdef INTRNG #ifdef SMP static inline struct intr_ipi * intr_ipi_lookup(u_int ipi) diff --git a/sys/arm/arm/mp_machdep.c b/sys/arm/arm/mp_machdep.c index 699881c753de..db52622ef014 100644 --- a/sys/arm/arm/mp_machdep.c +++ b/sys/arm/arm/mp_machdep.c @@ -74,7 +74,7 @@ volatile int mp_naps; /* Set to 1 once we're ready to let the APs out of the pen. */ volatile int aps_ready = 0; -#ifndef ARM_INTRNG +#ifndef INTRNG static int ipi_handler(void *arg); #endif void set_stackptrs(int cpu); @@ -152,7 +152,7 @@ init_secondary(int cpu) { struct pcpu *pc; uint32_t loop_counter; -#ifndef ARM_INTRNG +#ifndef INTRNG int start = 0, end = 0; #endif uint32_t actlr_mask, actlr_set; @@ -207,7 +207,7 @@ init_secondary(int cpu) mtx_unlock_spin(&ap_boot_mtx); -#ifndef ARM_INTRNG +#ifndef INTRNG /* Enable ipi */ #ifdef IPI_IRQ_START start = IPI_IRQ_START; @@ -243,7 +243,7 @@ init_secondary(int cpu) /* NOTREACHED */ } -#ifdef ARM_INTRNG +#ifdef INTRNG static void ipi_rendezvous(void *dummy __unused) { @@ -421,14 +421,14 @@ static void release_aps(void *dummy __unused) { uint32_t loop_counter; -#ifndef ARM_INTRNG +#ifndef INTRNG int start = 0, end = 0; #endif if (mp_ncpus == 1) return; -#ifdef ARM_INTRNG +#ifdef INTRNG intr_pic_ipi_setup(IPI_RENDEZVOUS, "rendezvous", ipi_rendezvous, NULL); intr_pic_ipi_setup(IPI_AST, "ast", ipi_ast, NULL); intr_pic_ipi_setup(IPI_STOP, "stop", ipi_stop, NULL); @@ -501,7 +501,7 @@ ipi_all_but_self(u_int ipi) other_cpus = all_cpus; CPU_CLR(PCPU_GET(cpuid), &other_cpus); CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi); -#ifdef ARM_INTRNG +#ifdef INTRNG intr_ipi_send(other_cpus, ipi); #else pic_ipi_send(other_cpus, ipi); @@ -517,7 +517,7 @@ ipi_cpu(int cpu, u_int ipi) CPU_SET(cpu, &cpus); CTR3(KTR_SMP, "%s: cpu: %d, ipi: %x", __func__, cpu, ipi); -#ifdef ARM_INTRNG +#ifdef INTRNG intr_ipi_send(cpus, ipi); #else pic_ipi_send(cpus, ipi); @@ -529,7 +529,7 @@ ipi_selected(cpuset_t cpus, u_int ipi) { CTR2(KTR_SMP, "%s: ipi: %x", __func__, ipi); -#ifdef ARM_INTRNG +#ifdef INTRNG intr_ipi_send(cpus, ipi); #else pic_ipi_send(cpus, ipi); diff --git a/sys/arm/arm/nexus.c b/sys/arm/arm/nexus.c index 81f7b020f3e3..a84e0a804334 100644 --- a/sys/arm/arm/nexus.c +++ b/sys/arm/arm/nexus.c @@ -86,14 +86,14 @@ static struct resource *nexus_alloc_resource(device_t, device_t, int, int *, static int nexus_activate_resource(device_t, device_t, int, int, struct resource *); static bus_space_tag_t nexus_get_bus_tag(device_t, device_t); -#ifdef ARM_INTRNG +#ifdef INTRNG #ifdef SMP static int nexus_bind_intr(device_t, device_t, struct resource *, int); #endif #endif static int nexus_config_intr(device_t dev, int irq, enum intr_trigger trig, enum intr_polarity pol); -#ifdef ARM_INTRNG +#ifdef INTRNG static int nexus_describe_intr(device_t dev, device_t child, struct resource *irq, void *cookie, const char *descr); #endif @@ -126,7 +126,7 @@ static device_method_t nexus_methods[] = { DEVMETHOD(bus_setup_intr, nexus_setup_intr), DEVMETHOD(bus_teardown_intr, nexus_teardown_intr), DEVMETHOD(bus_get_bus_tag, nexus_get_bus_tag), -#ifdef ARM_INTRNG +#ifdef INTRNG DEVMETHOD(bus_describe_intr, nexus_describe_intr), #ifdef SMP DEVMETHOD(bus_bind_intr, nexus_bind_intr), @@ -280,7 +280,7 @@ nexus_config_intr(device_t dev, int irq, enum intr_trigger trig, { int ret = ENODEV; -#ifdef ARM_INTRNG +#ifdef INTRNG device_printf(dev, "bus_config_intr is obsolete and not supported!\n"); ret = EOPNOTSUPP; #else @@ -294,14 +294,14 @@ static int nexus_setup_intr(device_t dev, device_t child, struct resource *res, int flags, driver_filter_t *filt, driver_intr_t *intr, void *arg, void **cookiep) { -#ifndef ARM_INTRNG +#ifndef INTRNG int irq; #endif if ((rman_get_flags(res) & RF_SHAREABLE) == 0) flags |= INTR_EXCL; -#ifdef ARM_INTRNG +#ifdef INTRNG return(intr_setup_irq(child, res, filt, intr, arg, flags, cookiep)); #else for (irq = rman_get_start(res); irq <= rman_get_end(res); irq++) { @@ -317,14 +317,14 @@ static int nexus_teardown_intr(device_t dev, device_t child, struct resource *r, void *ih) { -#ifdef ARM_INTRNG +#ifdef INTRNG return (intr_teardown_irq(child, r, ih)); #else return (arm_remove_irqhandler(rman_get_start(r), ih)); #endif } -#ifdef ARM_INTRNG +#ifdef INTRNG static int nexus_describe_intr(device_t dev, device_t child, struct resource *irq, void *cookie, const char *descr) diff --git a/sys/arm/at91/at91_common.c b/sys/arm/at91/at91_common.c index bc13196bffb1..37f94d72c8a6 100644 --- a/sys/arm/at91/at91_common.c +++ b/sys/arm/at91/at91_common.c @@ -53,7 +53,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_aic_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/broadcom/bcm2835/bcm2835_common.c b/sys/arm/broadcom/bcm2835/bcm2835_common.c index bcb84b792481..e7ce52b2a898 100644 --- a/sys/arm/broadcom/bcm2835/bcm2835_common.c +++ b/sys/arm/broadcom/bcm2835/bcm2835_common.c @@ -50,7 +50,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_intc_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) @@ -78,4 +78,4 @@ fdt_pic_decode_t fdt_pic_table[] = { &fdt_intc_decode_ic, NULL }; -#endif /* ARM_INTRNG */ +#endif /* INTRNG */ diff --git a/sys/arm/broadcom/bcm2835/bcm2835_gpio.c b/sys/arm/broadcom/bcm2835/bcm2835_gpio.c index d448fc5cd4ed..7c67a3813cb1 100644 --- a/sys/arm/broadcom/bcm2835/bcm2835_gpio.c +++ b/sys/arm/broadcom/bcm2835/bcm2835_gpio.c @@ -53,7 +53,7 @@ __FBSDID("$FreeBSD$"); #include "gpio_if.h" -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #endif @@ -84,7 +84,7 @@ struct bcm_gpio_sysctl { uint32_t pin; }; -#ifdef ARM_INTRNG +#ifdef INTRNG struct bcm_gpio_irqsrc { struct intr_irqsrc bgi_isrc; uint32_t bgi_irq; @@ -105,11 +105,11 @@ struct bcm_gpio_softc { int sc_ro_npins; int sc_ro_pins[BCM_GPIO_PINS]; struct gpio_pin sc_gpio_pins[BCM_GPIO_PINS]; -#ifndef ARM_INTRNG +#ifndef INTRNG struct intr_event * sc_events[BCM_GPIO_PINS]; #endif struct bcm_gpio_sysctl sc_sysctl[BCM_GPIO_PINS]; -#ifdef ARM_INTRNG +#ifdef INTRNG struct bcm_gpio_irqsrc sc_isrcs[BCM_GPIO_PINS]; #else enum intr_trigger sc_irq_trigger[BCM_GPIO_PINS]; @@ -153,7 +153,7 @@ enum bcm_gpio_pud { static struct bcm_gpio_softc *bcm_gpio_sc = NULL; -#ifdef ARM_INTRNG +#ifdef INTRNG static int bcm_gpio_intr_bank0(void *arg); static int bcm_gpio_intr_bank1(void *arg); static int bcm_gpio_pic_attach(struct bcm_gpio_softc *sc); @@ -691,7 +691,7 @@ bcm_gpio_get_reserved_pins(struct bcm_gpio_softc *sc) return (0); } -#ifndef ARM_INTRNG +#ifndef INTRNG static int bcm_gpio_intr(void *arg) { @@ -741,7 +741,7 @@ bcm_gpio_probe(device_t dev) return (BUS_PROBE_DEFAULT); } -#ifdef ARM_INTRNG +#ifdef INTRNG static int bcm_gpio_intr_attach(device_t dev) { @@ -862,7 +862,7 @@ bcm_gpio_attach(device_t dev) sc->sc_gpio_pins[i].gp_pin = j; sc->sc_gpio_pins[i].gp_caps = BCM_GPIO_DEFAULT_CAPS; sc->sc_gpio_pins[i].gp_flags = bcm_gpio_func_flag(func); -#ifndef ARM_INTRNG +#ifndef INTRNG /* The default is active-low interrupts. */ sc->sc_irq_trigger[i] = INTR_TRIGGER_LEVEL; sc->sc_irq_polarity[i] = INTR_POLARITY_LOW; @@ -892,7 +892,7 @@ bcm_gpio_detach(device_t dev) return (EBUSY); } -#ifdef ARM_INTRNG +#ifdef INTRNG static inline void bcm_gpio_isrc_eoi(struct bcm_gpio_softc *sc, struct bcm_gpio_irqsrc *bgi) { @@ -1372,7 +1372,7 @@ static device_method_t bcm_gpio_methods[] = { DEVMETHOD(gpio_pin_set, bcm_gpio_pin_set), DEVMETHOD(gpio_pin_toggle, bcm_gpio_pin_toggle), -#ifdef ARM_INTRNG +#ifdef INTRNG /* Interrupt controller interface */ DEVMETHOD(pic_disable_intr, bcm_gpio_pic_disable_intr), DEVMETHOD(pic_enable_intr, bcm_gpio_pic_enable_intr), diff --git a/sys/arm/broadcom/bcm2835/bcm2835_intr.c b/sys/arm/broadcom/bcm2835/bcm2835_intr.c index 936dc529deb7..8124c968575f 100644 --- a/sys/arm/broadcom/bcm2835/bcm2835_intr.c +++ b/sys/arm/broadcom/bcm2835/bcm2835_intr.c @@ -52,7 +52,7 @@ __FBSDID("$FreeBSD$"); #include #endif -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #endif @@ -105,7 +105,7 @@ __FBSDID("$FreeBSD$"); #define BANK1_END (BANK1_START + 32 - 1) #define BANK2_START (BANK1_START + 32) #define BANK2_END (BANK2_START + 32 - 1) -#ifndef ARM_INTRNG +#ifndef INTRNG #define BANK3_START (BANK2_START + 32) #define BANK3_END (BANK3_START + 32 - 1) #endif @@ -113,7 +113,7 @@ __FBSDID("$FreeBSD$"); #define IS_IRQ_BASIC(n) (((n) >= 0) && ((n) < BANK1_START)) #define IS_IRQ_BANK1(n) (((n) >= BANK1_START) && ((n) <= BANK1_END)) #define IS_IRQ_BANK2(n) (((n) >= BANK2_START) && ((n) <= BANK2_END)) -#ifndef ARM_INTRNG +#ifndef INTRNG #define ID_IRQ_BCM2836(n) (((n) >= BANK3_START) && ((n) <= BANK3_END)) #endif #define IRQ_BANK1(n) ((n) - BANK1_START) @@ -125,7 +125,7 @@ __FBSDID("$FreeBSD$"); #define dprintf(fmt, args...) #endif -#ifdef ARM_INTRNG +#ifdef INTRNG #define BCM_INTC_NIRQS 72 /* 8 + 32 + 32 */ struct bcm_intc_irqsrc { @@ -142,7 +142,7 @@ struct bcm_intc_softc { struct resource * intc_res; bus_space_tag_t intc_bst; bus_space_handle_t intc_bsh; -#ifdef ARM_INTRNG +#ifdef INTRNG struct resource * intc_irq_res; void * intc_irq_hdl; struct bcm_intc_irqsrc intc_isrcs[BCM_INTC_NIRQS]; @@ -156,7 +156,7 @@ static struct bcm_intc_softc *bcm_intc_sc = NULL; #define intc_write_4(_sc, reg, val) \ bus_space_write_4((_sc)->intc_bst, (_sc)->intc_bsh, (reg), (val)) -#ifdef ARM_INTRNG +#ifdef INTRNG static inline void bcm_intc_isrc_mask(struct bcm_intc_softc *sc, struct bcm_intc_irqsrc *bii) { @@ -360,7 +360,7 @@ bcm_intc_attach(device_t dev) { struct bcm_intc_softc *sc = device_get_softc(dev); int rid = 0; -#ifdef ARM_INTRNG +#ifdef INTRNG intptr_t xref; #endif sc->sc_dev = dev; @@ -374,7 +374,7 @@ bcm_intc_attach(device_t dev) return (ENXIO); } -#ifdef ARM_INTRNG +#ifdef INTRNG xref = OF_xref_from_node(ofw_bus_get_node(dev)); if (bcm_intc_pic_register(sc, xref) != 0) { bus_release_resource(dev, SYS_RES_MEMORY, 0, sc->intc_res); @@ -412,7 +412,7 @@ static device_method_t bcm_intc_methods[] = { DEVMETHOD(device_probe, bcm_intc_probe), DEVMETHOD(device_attach, bcm_intc_attach), -#ifdef ARM_INTRNG +#ifdef INTRNG DEVMETHOD(pic_disable_intr, bcm_intc_disable_intr), DEVMETHOD(pic_enable_intr, bcm_intc_enable_intr), DEVMETHOD(pic_map_intr, bcm_intc_map_intr), @@ -434,7 +434,7 @@ static devclass_t bcm_intc_devclass; DRIVER_MODULE(intc, simplebus, bcm_intc_driver, bcm_intc_devclass, 0, 0); -#ifndef ARM_INTRNG +#ifndef INTRNG int arm_get_next_irq(int last_irq) { diff --git a/sys/arm/broadcom/bcm2835/bcm2836.c b/sys/arm/broadcom/bcm2835/bcm2836.c index f9a2fcc62f44..16c1e4b74e14 100644 --- a/sys/arm/broadcom/bcm2835/bcm2836.c +++ b/sys/arm/broadcom/bcm2835/bcm2836.c @@ -53,7 +53,7 @@ __FBSDID("$FreeBSD$"); #include #include -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #else #include @@ -72,7 +72,7 @@ __FBSDID("$FreeBSD$"); #define MAILBOX0_IRQEN (1 << 0) #endif -#ifdef ARM_INTRNG +#ifdef INTRNG #define BCM_LINTC_CONTROL_REG 0x00 #define BCM_LINTC_PRESCALER_REG 0x08 #define BCM_LINTC_GPU_ROUTING_REG 0x0c diff --git a/sys/arm/broadcom/bcm2835/bcm2836.h b/sys/arm/broadcom/bcm2835/bcm2836.h index 14abfe2e49b7..6068975ee79f 100644 --- a/sys/arm/broadcom/bcm2835/bcm2836.h +++ b/sys/arm/broadcom/bcm2835/bcm2836.h @@ -30,7 +30,7 @@ #ifndef _BCM2815_BCM2836_H #define _BCM2815_BCM2836_H -#ifndef ARM_INTRNG +#ifndef INTRNG #define BCM2836_GPU_IRQ 8 int bcm2836_get_next_irq(int); diff --git a/sys/arm/broadcom/bcm2835/bcm2836_mp.c b/sys/arm/broadcom/bcm2835/bcm2836_mp.c index a361319a115b..bbbc514a2893 100644 --- a/sys/arm/broadcom/bcm2835/bcm2836_mp.c +++ b/sys/arm/broadcom/bcm2835/bcm2836_mp.c @@ -139,7 +139,7 @@ platform_mp_start_ap(void) } } -#ifndef ARM_INTRNG +#ifndef INTRNG void pic_ipi_send(cpuset_t cpus, u_int ipi) { diff --git a/sys/arm/conf/A20 b/sys/arm/conf/A20 index 8f56523c2c6c..f28080c623f5 100644 --- a/sys/arm/conf/A20 +++ b/sys/arm/conf/A20 @@ -23,7 +23,7 @@ ident A20 include "std.armv6" include "../allwinner/a20/std.a20" -options ARM_INTRNG +options INTRNG options SOC_ALLWINNER_A20 diff --git a/sys/arm/conf/ALPINE b/sys/arm/conf/ALPINE index fa3086542fe8..55e4468d3df7 100644 --- a/sys/arm/conf/ALPINE +++ b/sys/arm/conf/ALPINE @@ -37,7 +37,7 @@ options DDB #Enable the kernel debugger # Interrupt controller device gic -options ARM_INTRNG +options INTRNG # Pseudo devices device loop diff --git a/sys/arm/conf/ARMADA38X b/sys/arm/conf/ARMADA38X index 13c3aa264baf..1903e62d961f 100644 --- a/sys/arm/conf/ARMADA38X +++ b/sys/arm/conf/ARMADA38X @@ -62,7 +62,7 @@ device pci # Interrupt controllers device gic -options ARM_INTRNG +options INTRNG # Timers device mpcore_timer diff --git a/sys/arm/conf/BEAGLEBONE b/sys/arm/conf/BEAGLEBONE index 1885c0c94437..4497b0ff8303 100644 --- a/sys/arm/conf/BEAGLEBONE +++ b/sys/arm/conf/BEAGLEBONE @@ -28,7 +28,7 @@ include "../ti/am335x/std.am335x" makeoptions MODULES_EXTRA="dtb/am335x am335x_dmtpps" -options ARM_INTRNG +options INTRNG options HZ=100 options SCHED_4BSD # 4BSD scheduler diff --git a/sys/arm/conf/EXYNOS5.common b/sys/arm/conf/EXYNOS5.common index 770a69088666..c9979160edb8 100644 --- a/sys/arm/conf/EXYNOS5.common +++ b/sys/arm/conf/EXYNOS5.common @@ -87,7 +87,7 @@ device dwmmc # Interrupt controller device gic -options ARM_INTRNG +options INTRNG # ARM Generic Timer device generic_timer diff --git a/sys/arm/conf/IMX6 b/sys/arm/conf/IMX6 index 6b383e28ccfd..bc1145f4c65f 100644 --- a/sys/arm/conf/IMX6 +++ b/sys/arm/conf/IMX6 @@ -22,7 +22,7 @@ ident IMX6 include "std.armv6" include "../freescale/imx/std.imx6" -options ARM_INTRNG +options INTRNG options SOC_IMX6 diff --git a/sys/arm/conf/ODROIDC1 b/sys/arm/conf/ODROIDC1 index 550da8702e27..16802d31f5c8 100644 --- a/sys/arm/conf/ODROIDC1 +++ b/sys/arm/conf/ODROIDC1 @@ -26,7 +26,7 @@ options SMP # Enable multiple cores # Interrupt controller device gic -options ARM_INTRNG +options INTRNG options FDT_DTB_STATIC makeoptions FDT_DTS_FILE=odroidc1.dts diff --git a/sys/arm/conf/PANDABOARD b/sys/arm/conf/PANDABOARD index 4eaa471e35dc..69a82525701e 100644 --- a/sys/arm/conf/PANDABOARD +++ b/sys/arm/conf/PANDABOARD @@ -60,7 +60,7 @@ options DDB # Enable the kernel debugger device fdt_pinctrl # Interrupt controller device gic -options ARM_INTRNG +options INTRNG # ARM MPCore timer device mpcore_timer diff --git a/sys/arm/conf/RK3188 b/sys/arm/conf/RK3188 index ec6ddb86b1ca..e3e5ac8fcf36 100644 --- a/sys/arm/conf/RK3188 +++ b/sys/arm/conf/RK3188 @@ -47,7 +47,7 @@ options ROOTDEVNAME=\"ufs:/dev/mmcsd0\" # Interrupt controller device gic -options ARM_INTRNG +options INTRNG # ARM MPCore timer device mpcore_timer diff --git a/sys/arm/conf/RPI-B b/sys/arm/conf/RPI-B index 9bc2636e0919..5f6bc2769064 100644 --- a/sys/arm/conf/RPI-B +++ b/sys/arm/conf/RPI-B @@ -24,7 +24,7 @@ include "std.armv6" include "../broadcom/bcm2835/std.rpi" include "../broadcom/bcm2835/std.bcm2835" -options ARM_INTRNG +options INTRNG options HZ=100 options SCHED_4BSD # 4BSD scheduler diff --git a/sys/arm/conf/RPI2 b/sys/arm/conf/RPI2 index 3cee50d3f1ff..e669580d9055 100644 --- a/sys/arm/conf/RPI2 +++ b/sys/arm/conf/RPI2 @@ -24,7 +24,7 @@ include "std.armv6" include "../broadcom/bcm2835/std.rpi" include "../broadcom/bcm2835/std.bcm2836" -options ARM_INTRNG +options INTRNG options HZ=100 options SCHED_ULE # ULE scheduler diff --git a/sys/arm/conf/SOCKIT.common b/sys/arm/conf/SOCKIT.common index 3365929d9d68..3db9457c7fec 100644 --- a/sys/arm/conf/SOCKIT.common +++ b/sys/arm/conf/SOCKIT.common @@ -53,7 +53,7 @@ options INVARIANT_SUPPORT # Extra sanity checks of internal structures, require # Interrupt controller device gic -options ARM_INTRNG +options INTRNG # ARM MPCore timer device mpcore_timer diff --git a/sys/arm/conf/VIRT b/sys/arm/conf/VIRT index aabe6369157f..374af8726b4b 100644 --- a/sys/arm/conf/VIRT +++ b/sys/arm/conf/VIRT @@ -47,7 +47,7 @@ options INVARIANT_SUPPORT # Extra sanity checks of internal structures, require # Interrupt controller device gic -options ARM_INTRNG +options INTRNG # ARM Generic Timer device generic_timer diff --git a/sys/arm/conf/VSATV102 b/sys/arm/conf/VSATV102 index 96e3ba4a703d..c08060a3bcac 100644 --- a/sys/arm/conf/VSATV102 +++ b/sys/arm/conf/VSATV102 @@ -26,7 +26,7 @@ options SMP # Enable multiple cores # Interrupt controller device gic -options ARM_INTRNG +options INTRNG options FDT_DTB_STATIC makeoptions FDT_DTS_FILE=vsatv102-m6.dts diff --git a/sys/arm/conf/VYBRID b/sys/arm/conf/VYBRID index 471b8d5bda6c..3e15e42a7a25 100644 --- a/sys/arm/conf/VYBRID +++ b/sys/arm/conf/VYBRID @@ -62,7 +62,7 @@ options NO_SWAPPING # Interrupt controller device gic -options ARM_INTRNG +options INTRNG # ARM MPCore timer device mpcore_timer diff --git a/sys/arm/conf/ZEDBOARD b/sys/arm/conf/ZEDBOARD index 41ec23a82ef5..1c024cc0414e 100644 --- a/sys/arm/conf/ZEDBOARD +++ b/sys/arm/conf/ZEDBOARD @@ -52,7 +52,7 @@ options ROOTDEVNAME=\"ufs:mmcsd0s2a\" # Interrupt controller device gic -options ARM_INTRNG +options INTRNG # Cache controller device pl310 # PL310 L2 cache controller diff --git a/sys/arm/freescale/imx/imx6_machdep.c b/sys/arm/freescale/imx/imx6_machdep.c index 061355dce1fa..d5417c2fb35f 100644 --- a/sys/arm/freescale/imx/imx6_machdep.c +++ b/sys/arm/freescale/imx/imx6_machdep.c @@ -58,7 +58,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { static uint32_t gpio1_node; -#ifndef ARM_INTRNG +#ifndef INTRNG /* * Work around the linux workaround for imx6 erratum 006687, in which some * ethernet interrupts don't go to the GPC and thus won't wake the system from diff --git a/sys/arm/freescale/imx/imx_common.c b/sys/arm/freescale/imx/imx_common.c index 50922e6aab4b..c423873c80c3 100644 --- a/sys/arm/freescale/imx/imx_common.c +++ b/sys/arm/freescale/imx/imx_common.c @@ -54,7 +54,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_intc_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) @@ -71,4 +71,4 @@ fdt_pic_decode_t fdt_pic_table[] = { &fdt_intc_decode_ic, NULL }; -#endif /* ARM_INTRNG */ +#endif /* INTRNG */ diff --git a/sys/arm/freescale/imx/imx_gpio.c b/sys/arm/freescale/imx/imx_gpio.c index df0f2addda5f..ba82f5c4a01a 100644 --- a/sys/arm/freescale/imx/imx_gpio.c +++ b/sys/arm/freescale/imx/imx_gpio.c @@ -60,7 +60,7 @@ __FBSDID("$FreeBSD$"); #include "gpio_if.h" -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #endif @@ -91,7 +91,7 @@ __FBSDID("$FreeBSD$"); #define DEFAULT_CAPS (GPIO_PIN_INPUT | GPIO_PIN_OUTPUT) #define NGPIO 32 -#ifdef ARM_INTRNG +#ifdef INTRNG struct gpio_irqsrc { struct intr_irqsrc gi_isrc; u_int gi_irq; @@ -110,7 +110,7 @@ struct imx51_gpio_softc { bus_space_handle_t sc_ioh; int gpio_npins; struct gpio_pin gpio_pins[NGPIO]; -#ifdef ARM_INTRNG +#ifdef INTRNG struct gpio_irqsrc gpio_pic_irqsrc[NGPIO]; #endif }; @@ -155,7 +155,7 @@ static int imx51_gpio_pin_set(device_t, uint32_t, unsigned int); static int imx51_gpio_pin_get(device_t, uint32_t, unsigned int *); static int imx51_gpio_pin_toggle(device_t, uint32_t pin); -#ifdef ARM_INTRNG +#ifdef INTRNG static int gpio_pic_map_fdt(device_t dev, u_int ncells, pcell_t *cells, u_int *irqp, enum intr_polarity *polp, enum intr_trigger *trigp) @@ -653,7 +653,7 @@ imx51_gpio_attach(device_t dev) */ WRITE4(sc, IMX_GPIO_IMR_REG, 0); for (irq = 0; irq < 2; irq++) { -#ifdef ARM_INTRNG +#ifdef INTRNG if ((bus_setup_intr(dev, sc->sc_res[1 + irq], INTR_TYPE_CLK, gpio_pic_filter, NULL, sc, &sc->gpio_ih[irq]))) { device_printf(dev, @@ -675,7 +675,7 @@ imx51_gpio_attach(device_t dev) "imx_gpio%d.%d", unit, i); } -#ifdef ARM_INTRNG +#ifdef INTRNG gpio_pic_register_isrcs(sc); intr_pic_register(dev, OF_xref_from_node(ofw_bus_get_node(dev))); #endif @@ -713,7 +713,7 @@ static device_method_t imx51_gpio_methods[] = { DEVMETHOD(device_attach, imx51_gpio_attach), DEVMETHOD(device_detach, imx51_gpio_detach), -#ifdef ARM_INTRNG +#ifdef INTRNG /* Interrupt controller interface */ DEVMETHOD(pic_disable_intr, gpio_pic_disable_intr), DEVMETHOD(pic_enable_intr, gpio_pic_enable_intr), diff --git a/sys/arm/freescale/vybrid/vf_common.c b/sys/arm/freescale/vybrid/vf_common.c index 913902a71cb5..494f5d60e0c1 100644 --- a/sys/arm/freescale/vybrid/vf_common.c +++ b/sys/arm/freescale/vybrid/vf_common.c @@ -66,7 +66,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_pic_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/include/intr.h b/sys/arm/include/intr.h index e81bc7dd7ab7..7a91525a909d 100644 --- a/sys/arm/include/intr.h +++ b/sys/arm/include/intr.h @@ -43,7 +43,7 @@ #include #endif -#ifdef ARM_INTRNG +#ifdef INTRNG #ifndef NIRQ #define NIRQ 1024 /* XXX - It should be an option. */ @@ -63,7 +63,7 @@ void intr_ipi_setup(u_int, const char *, intr_ipi_handler_t *, void *, int intr_pic_ipi_setup(u_int, const char *, intr_ipi_handler_t *, void *); #endif -#else /* ARM_INTRNG */ +#else /* INTRNG */ /* XXX move to std.* files? */ #ifdef CPU_XSCALE_81342 @@ -111,7 +111,7 @@ int gic_decode_fdt(phandle_t, pcell_t *, int *, int *, int *); int intr_fdt_map_irq(phandle_t, pcell_t *, int); #endif -#endif /* ARM_INTRNG */ +#endif /* INTRNG */ void arm_irq_memory_barrier(uintptr_t); diff --git a/sys/arm/include/smp.h b/sys/arm/include/smp.h index e685cc36755e..704fffa961a5 100644 --- a/sys/arm/include/smp.h +++ b/sys/arm/include/smp.h @@ -6,7 +6,7 @@ #include #include -#ifdef ARM_INTRNG +#ifdef INTRNG enum { IPI_AST, IPI_PREEMPT, @@ -37,7 +37,7 @@ void ipi_cpu(int cpu, u_int ipi); void ipi_selected(cpuset_t cpus, u_int ipi); /* PIC interface */ -#ifndef ARM_INTRNG +#ifndef INTRNG void pic_ipi_send(cpuset_t cpus, u_int ipi); void pic_ipi_clear(int ipi); int pic_ipi_read(int arg); diff --git a/sys/arm/lpc/lpc_intc.c b/sys/arm/lpc/lpc_intc.c index d4b25172fa63..db7c300aa326 100644 --- a/sys/arm/lpc/lpc_intc.c +++ b/sys/arm/lpc/lpc_intc.c @@ -231,7 +231,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_pic_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/mv/mpic.c b/sys/arm/mv/mpic.c index 4f246a47ba0d..4c5856a6dc8f 100644 --- a/sys/arm/mv/mpic.c +++ b/sys/arm/mv/mpic.c @@ -60,7 +60,7 @@ __FBSDID("$FreeBSD$"); #include #include -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #endif @@ -98,7 +98,7 @@ __FBSDID("$FreeBSD$"); #define MPIC_PPI 32 -#ifdef ARM_INTRNG +#ifdef INTRNG struct mv_mpic_irqsrc { struct intr_irqsrc mmi_isrc; u_int mmi_irq; @@ -115,7 +115,7 @@ struct mv_mpic_softc { bus_space_tag_t drbl_bst; bus_space_handle_t drbl_bsh; struct mtx mtx; -#ifdef ARM_INTRNG +#ifdef INTRNG struct mv_mpic_irqsrc * mpic_isrcs; #endif int nirqs; @@ -151,7 +151,7 @@ static void mpic_mask_irq_err(uintptr_t nb); static void mpic_unmask_irq_err(uintptr_t nb); static int mpic_intr(void *arg); static void mpic_unmask_msi(void); -#ifndef ARM_INTRNG +#ifndef INTRNG static void arm_mask_irq_err(uintptr_t); static void arm_unmask_irq_err(uintptr_t); #endif @@ -185,7 +185,7 @@ mv_mpic_probe(device_t dev) return (0); } -#ifdef ARM_INTRNG +#ifdef INTRNG static int mv_mpic_register_isrcs(struct mv_mpic_softc *sc) { @@ -241,7 +241,7 @@ mv_mpic_attach(device_t dev) device_printf(dev, "could not allocate resources\n"); return (ENXIO); } -#ifdef ARM_INTRNG +#ifdef INTRNG if (sc->mpic_res[3] == NULL) device_printf(dev, "No interrupt to use.\n"); else @@ -268,7 +268,7 @@ mv_mpic_attach(device_t dev) val = MPIC_READ(mv_mpic_sc, MPIC_CTRL); sc->nirqs = MPIC_CTRL_NIRQS(val); -#ifdef ARM_INTRNG +#ifdef INTRNG if (mv_mpic_register_isrcs(sc) != 0) { device_printf(dev, "could not register PIC ISRCs\n"); bus_release_resources(dev, mv_mpic_spec, sc->mpic_res); @@ -286,7 +286,7 @@ mv_mpic_attach(device_t dev) return (0); } -#ifdef ARM_INTRNG +#ifdef INTRNG static int mpic_intr(void *arg) { @@ -370,7 +370,7 @@ static device_method_t mv_mpic_methods[] = { DEVMETHOD(device_probe, mv_mpic_probe), DEVMETHOD(device_attach, mv_mpic_attach), -#ifdef ARM_INTRNG +#ifdef INTRNG DEVMETHOD(pic_disable_intr, mpic_disable_intr), DEVMETHOD(pic_enable_intr, mpic_enable_intr), DEVMETHOD(pic_map_intr, mpic_map_intr), @@ -391,7 +391,7 @@ static devclass_t mv_mpic_devclass; EARLY_DRIVER_MODULE(mpic, simplebus, mv_mpic_driver, mv_mpic_devclass, 0, 0, BUS_PASS_INTERRUPT); -#ifndef ARM_INTRNG +#ifndef INTRNG int arm_get_next_irq(int last) { diff --git a/sys/arm/mv/mv_common.c b/sys/arm/mv/mv_common.c index a1d2a2d12667..5a1999347f05 100644 --- a/sys/arm/mv/mv_common.c +++ b/sys/arm/mv/mv_common.c @@ -2282,7 +2282,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_pic_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/nvidia/tegra124/std.tegra124 b/sys/arm/nvidia/tegra124/std.tegra124 index 127b001efd45..35de22534f46 100644 --- a/sys/arm/nvidia/tegra124/std.tegra124 +++ b/sys/arm/nvidia/tegra124/std.tegra124 @@ -6,7 +6,7 @@ makeoptions CONF_CFLAGS="-march=armv7a" options KERNVIRTADDR = 0xc0200000 makeoptions KERNVIRTADDR = 0xc0200000 -options ARM_INTRNG +options INTRNG options IPI_IRQ_START=0 options IPI_IRQ_END=15 diff --git a/sys/arm/qemu/virt_common.c b/sys/arm/qemu/virt_common.c index 572fee8e7fcb..03cba309308d 100644 --- a/sys/arm/qemu/virt_common.c +++ b/sys/arm/qemu/virt_common.c @@ -41,7 +41,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG fdt_pic_decode_t fdt_pic_table[] = { &gic_decode_fdt, NULL diff --git a/sys/arm/rockchip/rk30xx_common.c b/sys/arm/rockchip/rk30xx_common.c index 723c4291e039..aa66b72101a3 100644 --- a/sys/arm/rockchip/rk30xx_common.c +++ b/sys/arm/rockchip/rk30xx_common.c @@ -42,7 +42,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_aintc_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/samsung/exynos/exynos5_common.c b/sys/arm/samsung/exynos/exynos5_common.c index 8818f0453d40..b91e0830e1ec 100644 --- a/sys/arm/samsung/exynos/exynos5_common.c +++ b/sys/arm/samsung/exynos/exynos5_common.c @@ -53,7 +53,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_pic_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/ti/aintc.c b/sys/arm/ti/aintc.c index 8a544d00edbb..ebe486422e2d 100644 --- a/sys/arm/ti/aintc.c +++ b/sys/arm/ti/aintc.c @@ -48,7 +48,7 @@ __FBSDID("$FreeBSD$"); #include #include -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #endif @@ -68,7 +68,7 @@ __FBSDID("$FreeBSD$"); #define INTC_NIRQS 128 -#ifdef ARM_INTRNG +#ifdef INTRNG struct ti_aintc_irqsrc { struct intr_irqsrc tai_isrc; u_int tai_irq; @@ -81,7 +81,7 @@ struct ti_aintc_softc { bus_space_tag_t aintc_bst; bus_space_handle_t aintc_bsh; uint8_t ver; -#ifdef ARM_INTRNG +#ifdef INTRNG struct ti_aintc_irqsrc aintc_isrcs[INTC_NIRQS]; #endif }; @@ -105,7 +105,7 @@ static struct ofw_compat_data compat_data[] = { {NULL, 0}, }; -#ifdef ARM_INTRNG +#ifdef INTRNG static inline void ti_aintc_irq_eoi(struct ti_aintc_softc *sc) { @@ -295,7 +295,7 @@ ti_aintc_attach(device_t dev) /*Set Priority Threshold */ aintc_write_4(sc, INTC_THRESHOLD, 0xFF); -#ifndef ARM_INTRNG +#ifndef INTRNG arm_post_filter = aintc_post_filter; #else if (ti_aintc_pic_attach(sc) != 0) { @@ -310,7 +310,7 @@ static device_method_t ti_aintc_methods[] = { DEVMETHOD(device_probe, ti_aintc_probe), DEVMETHOD(device_attach, ti_aintc_attach), -#ifdef ARM_INTRNG +#ifdef INTRNG DEVMETHOD(pic_disable_intr, ti_aintc_disable_intr), DEVMETHOD(pic_enable_intr, ti_aintc_enable_intr), DEVMETHOD(pic_map_intr, ti_aintc_map_intr), @@ -334,7 +334,7 @@ EARLY_DRIVER_MODULE(aintc, simplebus, ti_aintc_driver, ti_aintc_devclass, 0, 0, BUS_PASS_INTERRUPT + BUS_PASS_ORDER_MIDDLE); SIMPLEBUS_PNP_INFO(compat_data); -#ifndef ARM_INTRNG +#ifndef INTRNG int arm_get_next_irq(int last_irq) { diff --git a/sys/arm/ti/ti_common.c b/sys/arm/ti/ti_common.c index aaf9a6a7bcf6..41c5a72c210c 100644 --- a/sys/arm/ti/ti_common.c +++ b/sys/arm/ti/ti_common.c @@ -53,7 +53,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG #ifdef SOC_TI_AM335X static int fdt_aintc_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, @@ -81,4 +81,4 @@ fdt_pic_decode_t fdt_pic_table[] = { #endif NULL }; -#endif /* !ARM_INTRNG */ +#endif /* !INTRNG */ diff --git a/sys/arm/ti/ti_gpio.c b/sys/arm/ti/ti_gpio.c index 633fbf0c0a03..54e50426027f 100644 --- a/sys/arm/ti/ti_gpio.c +++ b/sys/arm/ti/ti_gpio.c @@ -66,7 +66,7 @@ __FBSDID("$FreeBSD$"); #include "gpio_if.h" #include "ti_gpio_if.h" -#ifdef ARM_INTRNG +#ifdef INTRNG #include "pic_if.h" #endif @@ -121,7 +121,7 @@ __FBSDID("$FreeBSD$"); static int ti_gpio_intr(void *arg); static int ti_gpio_detach(device_t); -#ifdef ARM_INTRNG +#ifdef INTRNG static int ti_gpio_pic_attach(struct ti_gpio_softc *sc); static int ti_gpio_pic_detach(struct ti_gpio_softc *sc); #endif @@ -546,7 +546,7 @@ ti_gpio_pin_toggle(device_t dev, uint32_t pin) return (0); } -#ifndef ARM_INTRNG +#ifndef INTRNG /** * ti_gpio_intr - ISR for all GPIO modules * @arg: the soft context pointer @@ -655,7 +655,7 @@ static int ti_gpio_attach(device_t dev) { struct ti_gpio_softc *sc; -#ifndef ARM_INTRNG +#ifndef INTRNG unsigned int i; #endif int err; @@ -696,7 +696,7 @@ ti_gpio_attach(device_t dev) return (ENXIO); } -#ifdef ARM_INTRNG +#ifdef INTRNG if (ti_gpio_pic_attach(sc) != 0) { device_printf(dev, "WARNING: unable to attach PIC\n"); ti_gpio_detach(dev); @@ -771,7 +771,7 @@ ti_gpio_detach(device_t dev) if (sc->sc_mem_res != NULL) ti_gpio_intr_clr(sc, 0xffffffff); gpiobus_detach_bus(dev); -#ifdef ARM_INTRNG +#ifdef INTRNG if (sc->sc_isrcs != NULL) ti_gpio_pic_detach(sc); #else @@ -798,7 +798,7 @@ ti_gpio_detach(device_t dev) return (0); } -#ifdef ARM_INTRNG +#ifdef INTRNG static inline void ti_gpio_rwreg_set(struct ti_gpio_softc *sc, uint32_t reg, uint32_t mask) { @@ -1300,7 +1300,7 @@ static device_method_t ti_gpio_methods[] = { DEVMETHOD(gpio_pin_set, ti_gpio_pin_set), DEVMETHOD(gpio_pin_toggle, ti_gpio_pin_toggle), -#ifdef ARM_INTRNG +#ifdef INTRNG /* Interrupt controller interface */ DEVMETHOD(pic_disable_intr, ti_gpio_pic_disable_intr), DEVMETHOD(pic_enable_intr, ti_gpio_pic_enable_intr), diff --git a/sys/arm/ti/ti_gpio.h b/sys/arm/ti/ti_gpio.h index f16728b7c373..174dd62aaba0 100644 --- a/sys/arm/ti/ti_gpio.h +++ b/sys/arm/ti/ti_gpio.h @@ -39,7 +39,7 @@ */ #define MAX_GPIO_INTRS 8 -#ifndef ARM_INTRNG +#ifndef INTRNG struct ti_gpio_mask_arg { void *softc; int pin; @@ -61,7 +61,7 @@ struct ti_gpio_irqsrc { struct ti_gpio_softc { device_t sc_dev; device_t sc_busdev; -#ifndef ARM_INTRNG +#ifndef INTRNG /* Interrupt trigger type and level. */ enum intr_trigger *sc_irq_trigger; enum intr_polarity *sc_irq_polarity; @@ -74,7 +74,7 @@ struct ti_gpio_softc { struct resource *sc_mem_res; int sc_irq_rid; struct resource *sc_irq_res; -#ifndef ARM_INTRNG +#ifndef INTRNG /* Interrupt events. */ struct intr_event **sc_events; struct ti_gpio_mask_arg *sc_mask_args; diff --git a/sys/arm/versatile/versatile_common.c b/sys/arm/versatile/versatile_common.c index c47c298ce8d8..aca54b7eb8ee 100644 --- a/sys/arm/versatile/versatile_common.c +++ b/sys/arm/versatile/versatile_common.c @@ -50,7 +50,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_intc_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/arm/xilinx/zy7_machdep.c b/sys/arm/xilinx/zy7_machdep.c index 4b436839ecf0..dd179b7f6994 100644 --- a/sys/arm/xilinx/zy7_machdep.c +++ b/sys/arm/xilinx/zy7_machdep.c @@ -98,7 +98,7 @@ struct fdt_fixup_entry fdt_fixup_table[] = { { NULL, NULL } }; -#ifndef ARM_INTRNG +#ifndef INTRNG static int fdt_gic_decode_ic(phandle_t node, pcell_t *intr, int *interrupt, int *trig, int *pol) diff --git a/sys/conf/files.arm b/sys/conf/files.arm index ec1283a2b3d6..b77d1fc6988b 100644 --- a/sys/conf/files.arm +++ b/sys/conf/files.arm @@ -45,8 +45,8 @@ arm/arm/hdmi_if.m optional hdmi arm/arm/identcpu.c standard arm/arm/in_cksum.c optional inet | inet6 arm/arm/in_cksum_arm.S optional inet | inet6 -arm/arm/intr.c optional !arm_intrng -kern/subr_intr.c optional arm_intrng +arm/arm/intr.c optional !intrng +kern/subr_intr.c optional intrng arm/arm/locore.S standard no-obj arm/arm/machdep.c standard arm/arm/machdep_intr.c standard @@ -115,7 +115,7 @@ font.h optional sc \ compile-with "uudecode < /usr/share/syscons/fonts/${SC_DFLT_FONT}-8x16.fnt && file2c 'u_char dflt_font_16[16*256] = {' '};' < ${SC_DFLT_FONT}-8x16 > font.h && uudecode < /usr/share/syscons/fonts/${SC_DFLT_FONT}-8x14.fnt && file2c 'u_char dflt_font_14[14*256] = {' '};' < ${SC_DFLT_FONT}-8x14 >> font.h && uudecode < /usr/share/syscons/fonts/${SC_DFLT_FONT}-8x8.fnt && file2c 'u_char dflt_font_8[8*256] = {' '};' < ${SC_DFLT_FONT}-8x8 >> font.h" \ no-obj no-implicit-rule before-depend \ clean "font.h ${SC_DFLT_FONT}-8x14 ${SC_DFLT_FONT}-8x16 ${SC_DFLT_FONT}-8x8" -kern/pic_if.m optional arm_intrng +kern/pic_if.m optional intrng kern/subr_busdma_bufalloc.c standard kern/subr_sfbuf.c standard libkern/arm/aeabi_unwind.c standard diff --git a/sys/conf/options.arm b/sys/conf/options.arm index d6d7a377b894..4737b8019ee8 100644 --- a/sys/conf/options.arm +++ b/sys/conf/options.arm @@ -1,7 +1,6 @@ #$FreeBSD$ ARMV6 opt_global.h ARM_CACHE_LOCK_ENABLE opt_global.h -ARM_INTRNG opt_global.h ARM_KERN_DIRECTMAP opt_vm.h ARM_L2_PIPT opt_global.h ARM_MANY_BOARD opt_global.h @@ -24,6 +23,7 @@ DEV_PMU opt_global.h EFI opt_platform.h FLASHADDR opt_global.h GIC_DEFAULT_ICFGR_INIT opt_global.h +INTRNG opt_global.h IPI_IRQ_START opt_smp.h IPI_IRQ_END opt_smp.h FREEBSD_BOOT_LOADER opt_global.h diff --git a/sys/conf/options.mips b/sys/conf/options.mips index 10e2c1b24846..daae01f54466 100644 --- a/sys/conf/options.mips +++ b/sys/conf/options.mips @@ -144,5 +144,5 @@ PV_STATS opt_pmap.h # # Options to use INTRNG code # -MIPS_INTRNG opt_global.h +INTRNG opt_global.h MIPS_NIRQ opt_global.h diff --git a/sys/dev/fdt/fdt_common.h b/sys/dev/fdt/fdt_common.h index 17af3448e926..94f84ff3fe49 100644 --- a/sys/dev/fdt/fdt_common.h +++ b/sys/dev/fdt/fdt_common.h @@ -45,7 +45,7 @@ struct fdt_sense_level { enum intr_polarity pol; }; -#if defined(__arm__) && !defined(ARM_INTRNG) +#if defined(__arm__) && !defined(INTRNG) typedef int (*fdt_pic_decode_t)(phandle_t, pcell_t *, int *, int *, int *); extern fdt_pic_decode_t fdt_pic_table[]; #endif diff --git a/sys/mips/include/intr.h b/sys/mips/include/intr.h index e7258fe3078f..6e00643f4318 100644 --- a/sys/mips/include/intr.h +++ b/sys/mips/include/intr.h @@ -39,7 +39,7 @@ #ifndef _MACHINE_INTR_H_ #define _MACHINE_INTR_H_ -#ifdef MIPS_INTRNG +#ifdef INTRNG #ifdef FDT #include @@ -66,6 +66,6 @@ void cpu_establish_softintr(const char *, driver_filter_t *, void (*)(void*), /* MIPS interrupt C entry point */ void cpu_intr(struct trapframe *); -#endif /* MIPS_INTRNG */ +#endif /* INTRNG */ #endif /* _MACHINE_INTR_H */ diff --git a/sys/mips/include/smp.h b/sys/mips/include/smp.h index fa4cb5cc31de..d7a33de1e935 100644 --- a/sys/mips/include/smp.h +++ b/sys/mips/include/smp.h @@ -21,7 +21,7 @@ #include -#ifdef MIPS_INTRNG +#ifdef INTRNG # define MIPS_IPI_COUNT 1 # define INTR_IPI_COUNT MIPS_IPI_COUNT #endif diff --git a/sys/mips/mips/exception.S b/sys/mips/mips/exception.S index ebfd84d6ca20..ed02e5a274e6 100644 --- a/sys/mips/mips/exception.S +++ b/sys/mips/mips/exception.S @@ -646,7 +646,7 @@ NESTED_NOPROFILE(MipsKernIntr, KERN_EXC_FRAME_SIZE, ra) * Call the interrupt handler. a0 points at the saved frame. */ PTR_LA gp, _C_LABEL(_gp) -#ifdef MIPS_INTRNG +#ifdef INTRNG PTR_LA k0, _C_LABEL(intr_irq_handler) #else PTR_LA k0, _C_LABEL(cpu_intr) @@ -762,7 +762,7 @@ NESTED_NOPROFILE(MipsUserIntr, CALLFRAME_SIZ, ra) /* * Call the interrupt handler. */ -#ifdef MIPS_INTRNG +#ifdef INTRNG PTR_LA k0, _C_LABEL(intr_irq_handler) #else PTR_LA k0, _C_LABEL(cpu_intr) @@ -1198,7 +1198,7 @@ FPReturn: PTR_ADDU sp, sp, CALLFRAME_SIZ END(MipsFPTrap) -#ifndef MIPS_INTRNG +#ifndef INTRNG /* * Interrupt counters for vmstat. */ @@ -1225,7 +1225,7 @@ sintrcnt: #else .int INTRCNT_COUNT * (_MIPS_SZLONG / 8) * 2 #endif -#endif /* MIPS_INTRNG */ +#endif /* INTRNG */ /* diff --git a/sys/mips/mips/nexus.c b/sys/mips/mips/nexus.c index 908d5bca0dad..45e47ef7072f 100644 --- a/sys/mips/mips/nexus.c +++ b/sys/mips/mips/nexus.c @@ -57,7 +57,7 @@ __FBSDID("$FreeBSD$"); #include #include -#ifdef MIPS_INTRNG +#ifdef INTRNG #include #else #include @@ -115,7 +115,7 @@ static int nexus_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg, void **cookiep); static int nexus_teardown_intr(device_t, device_t, struct resource *, void *); -#ifdef MIPS_INTRNG +#ifdef INTRNG #ifdef SMP static int nexus_bind_intr(device_t, device_t, struct resource *, int); #endif @@ -148,7 +148,7 @@ static device_method_t nexus_methods[] = { DEVMETHOD(bus_activate_resource,nexus_activate_resource), DEVMETHOD(bus_deactivate_resource, nexus_deactivate_resource), DEVMETHOD(bus_hinted_child, nexus_hinted_child), -#ifdef MIPS_INTRNG +#ifdef INTRNG DEVMETHOD(bus_config_intr, nexus_config_intr), DEVMETHOD(bus_describe_intr, nexus_describe_intr), #ifdef SMP @@ -458,7 +458,7 @@ nexus_setup_intr(device_t dev, device_t child, struct resource *res, int flags, driver_filter_t *filt, driver_intr_t *intr, void *arg, void **cookiep) { -#ifdef MIPS_INTRNG +#ifdef INTRNG return (intr_setup_irq(child, res, filt, intr, arg, flags, cookiep)); #else int irq; @@ -483,7 +483,7 @@ static int nexus_teardown_intr(device_t dev, device_t child, struct resource *r, void *ih) { -#ifdef MIPS_INTRNG +#ifdef INTRNG return (intr_teardown_irq(child, r, ih)); #else printf("Unimplemented %s at %s:%d\n", __func__, __FILE__, __LINE__); @@ -491,7 +491,7 @@ nexus_teardown_intr(device_t dev, device_t child, struct resource *r, void *ih) #endif } -#ifdef MIPS_INTRNG +#ifdef INTRNG static int nexus_config_intr(device_t dev, int irq, enum intr_trigger trig, enum intr_polarity pol) @@ -527,7 +527,7 @@ nexus_ofw_map_intr(device_t dev, device_t child, phandle_t iparent, int icells, return (intr_fdt_map_irq(iparent, intr, icells)); } #endif -#endif /* MIPS_INTRNG */ +#endif /* INTRNG */ static void nexus_hinted_child(device_t bus, const char *dname, int dunit) diff --git a/sys/mips/mips/tick.c b/sys/mips/mips/tick.c index b146ad7d3116..8bcc534f8db8 100644 --- a/sys/mips/mips/tick.c +++ b/sys/mips/mips/tick.c @@ -51,7 +51,7 @@ __FBSDID("$FreeBSD$"); #include #include -#ifdef MIPS_INTRNG +#ifdef INTRNG #include #endif @@ -328,7 +328,7 @@ static int clock_attach(device_t dev) { struct clock_softc *sc; -#ifndef MIPS_INTRNG +#ifndef INTRNG int error; #endif @@ -336,7 +336,7 @@ clock_attach(device_t dev) panic("can't attach more clocks"); softc = sc = device_get_softc(dev); -#ifdef MIPS_INTRNG +#ifdef INTRNG cpu_establish_hardintr("clock", clock_intr, NULL, sc, 5, INTR_TYPE_CLK, NULL); #else From b85f65af68bd4c4d82b6d1591482978bafb4a951 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 16:10:11 +0000 Subject: [PATCH 126/143] kern: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/kern/kern_dump.c | 2 +- sys/kern/kern_kthread.c | 2 +- sys/kern/kern_proc.c | 2 +- sys/kern/kern_sysctl.c | 4 ++-- sys/kern/link_elf.c | 4 ++-- sys/kern/link_elf_obj.c | 4 ++-- sys/kern/sysv_sem.c | 4 ++-- sys/kern/uipc_mbuf.c | 2 +- sys/kern/uipc_sockbuf.c | 6 +++--- sys/kern/uipc_syscalls.c | 2 +- sys/kern/vfs_cluster.c | 2 +- sys/kern/vfs_export.c | 2 +- sys/kern/vfs_lookup.c | 4 ++-- sys/libkern/strtol.c | 2 +- sys/libkern/strtoq.c | 2 +- sys/libkern/strtoul.c | 2 +- sys/libkern/strtouq.c | 2 +- 17 files changed, 24 insertions(+), 24 deletions(-) diff --git a/sys/kern/kern_dump.c b/sys/kern/kern_dump.c index 1fd2fdd3ace5..c82272f09f71 100644 --- a/sys/kern/kern_dump.c +++ b/sys/kern/kern_dump.c @@ -174,7 +174,7 @@ dumpsys_cb_dumpdata(struct dump_pa *mdp, int seqnr, void *arg) error = 0; /* catch case in which chunk size is 0 */ counter = 0; /* Update twiddle every 16MB */ - va = 0; + va = NULL; pgs = mdp->pa_size / PAGE_SIZE; pa = mdp->pa_start; maxdumppgs = min(di->maxiosize / PAGE_SIZE, MAXDUMPPGS); diff --git a/sys/kern/kern_kthread.c b/sys/kern/kern_kthread.c index 134e9a22af70..7c0d6b5b0f9f 100644 --- a/sys/kern/kern_kthread.c +++ b/sys/kern/kern_kthread.c @@ -445,7 +445,7 @@ kproc_kthread_add(void (*func)(void *), void *arg, char buf[100]; struct thread *td; - if (*procptr == 0) { + if (*procptr == NULL) { error = kproc_create(func, arg, procptr, flags, pages, "%s", procname); if (error) diff --git a/sys/kern/kern_proc.c b/sys/kern/kern_proc.c index e980176abff2..9a41165b8f80 100644 --- a/sys/kern/kern_proc.c +++ b/sys/kern/kern_proc.c @@ -1444,7 +1444,7 @@ sysctl_kern_proc(SYSCTL_HANDLER_ARGS) p = LIST_FIRST(&allproc); else p = LIST_FIRST(&zombproc); - for (; p != 0; p = LIST_NEXT(p, p_list)) { + for (; p != NULL; p = LIST_NEXT(p, p_list)) { /* * Skip embryonic processes. */ diff --git a/sys/kern/kern_sysctl.c b/sys/kern/kern_sysctl.c index f57cd5889023..aae705e7b054 100644 --- a/sys/kern/kern_sysctl.c +++ b/sys/kern/kern_sysctl.c @@ -912,7 +912,7 @@ sysctl_sysctl_name(SYSCTL_HANDLER_ARGS) name++; continue; } - lsp2 = 0; + lsp2 = NULL; SLIST_FOREACH(oid, lsp, oid_link) { if (oid->oid_number != *name) continue; @@ -1083,7 +1083,7 @@ sysctl_sysctl_name2oid(SYSCTL_HANDLER_ARGS) { char *p; int error, oid[CTL_MAXNAME], len = 0; - struct sysctl_oid *op = 0; + struct sysctl_oid *op = NULL; struct rm_priotracker tracker; if (!req->newlen) diff --git a/sys/kern/link_elf.c b/sys/kern/link_elf.c index 1579c28dd3b1..349a95ef06c9 100644 --- a/sys/kern/link_elf.c +++ b/sys/kern/link_elf.c @@ -1382,7 +1382,7 @@ link_elf_search_symbol(linker_file_t lf, caddr_t value, u_long diff = off; u_long st_value; const Elf_Sym* es; - const Elf_Sym* best = 0; + const Elf_Sym* best = NULL; int i; for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) { @@ -1400,7 +1400,7 @@ link_elf_search_symbol(linker_file_t lf, caddr_t value, } } } - if (best == 0) + if (best == NULL) *diffp = off; else *diffp = diff; diff --git a/sys/kern/link_elf_obj.c b/sys/kern/link_elf_obj.c index 575a70607663..544bd253a6fc 100644 --- a/sys/kern/link_elf_obj.c +++ b/sys/kern/link_elf_obj.c @@ -1180,7 +1180,7 @@ link_elf_search_symbol(linker_file_t lf, caddr_t value, u_long diff = off; u_long st_value; const Elf_Sym *es; - const Elf_Sym *best = 0; + const Elf_Sym *best = NULL; int i; for (i = 0, es = ef->ddbsymtab; i < ef->ddbsymcnt; i++, es++) { @@ -1198,7 +1198,7 @@ link_elf_search_symbol(linker_file_t lf, caddr_t value, } } } - if (best == 0) + if (best == NULL) *diffp = off; else *diffp = diff; diff --git a/sys/kern/sysv_sem.c b/sys/kern/sysv_sem.c index 22616b988d88..0063916c5194 100644 --- a/sys/kern/sysv_sem.c +++ b/sys/kern/sysv_sem.c @@ -980,8 +980,8 @@ sys_semop(struct thread *td, struct semop_args *uap) size_t nsops = uap->nsops; struct sembuf *sops; struct semid_kernel *semakptr; - struct sembuf *sopptr = 0; - struct sem *semptr = 0; + struct sembuf *sopptr = NULL; + struct sem *semptr = NULL; struct sem_undo *suptr; struct mtx *sema_mtxp; size_t i, j, k; diff --git a/sys/kern/uipc_mbuf.c b/sys/kern/uipc_mbuf.c index 62dfda663cbd..84354f3454b7 100644 --- a/sys/kern/uipc_mbuf.c +++ b/sys/kern/uipc_mbuf.c @@ -459,7 +459,7 @@ m_copym(struct mbuf *m, int off0, int len, int wait) m = m->m_next; } np = ⊤ - top = 0; + top = NULL; while (len > 0) { if (m == NULL) { KASSERT(len == M_COPYALL, diff --git a/sys/kern/uipc_sockbuf.c b/sys/kern/uipc_sockbuf.c index 0cdd43ba7706..cf9f4b1f75fc 100644 --- a/sys/kern/uipc_sockbuf.c +++ b/sys/kern/uipc_sockbuf.c @@ -593,7 +593,7 @@ sbappend_locked(struct sockbuf *sb, struct mbuf *m, int flags) SOCKBUF_LOCK_ASSERT(sb); - if (m == 0) + if (m == NULL) return; sbm_clrprotoflags(m, flags); SBLASTRECORDCHK(sb); @@ -746,7 +746,7 @@ sbappendrecord_locked(struct sockbuf *sb, struct mbuf *m0) SOCKBUF_LOCK_ASSERT(sb); - if (m0 == 0) + if (m0 == NULL) return; m_clrprotoflags(m0); /* @@ -885,7 +885,7 @@ sbappendcontrol_locked(struct sockbuf *sb, struct mbuf *m0, SOCKBUF_LOCK_ASSERT(sb); - if (control == 0) + if (control == NULL) panic("sbappendcontrol_locked"); space = m_length(control, &n) + m_length(m0, NULL); diff --git a/sys/kern/uipc_syscalls.c b/sys/kern/uipc_syscalls.c index 79444e0e725e..05703ef65c15 100644 --- a/sys/kern/uipc_syscalls.c +++ b/sys/kern/uipc_syscalls.c @@ -430,7 +430,7 @@ kern_accept4(struct thread *td, int s, struct sockaddr **name, (void) fo_ioctl(nfp, FIONBIO, &tmp, td->td_ucred, td); tmp = fflag & FASYNC; (void) fo_ioctl(nfp, FIOASYNC, &tmp, td->td_ucred, td); - sa = 0; + sa = NULL; error = soaccept(so, &sa); if (error != 0) goto noconnection; diff --git a/sys/kern/vfs_cluster.c b/sys/kern/vfs_cluster.c index 40dc0c0c3203..ea902d7427f9 100644 --- a/sys/kern/vfs_cluster.c +++ b/sys/kern/vfs_cluster.c @@ -368,7 +368,7 @@ cluster_rbuild(struct vnode *vp, u_quad_t filesize, daddr_t lbn, return tbp; bp = trypbuf(&cluster_pbuf_freecnt); - if (bp == 0) + if (bp == NULL) return tbp; /* diff --git a/sys/kern/vfs_export.c b/sys/kern/vfs_export.c index 9eb523c212f5..e7a709d0e1e6 100644 --- a/sys/kern/vfs_export.c +++ b/sys/kern/vfs_export.c @@ -102,7 +102,7 @@ vfs_hang_addrlist(struct mount *mp, struct netexport *nep, register struct radix_node_head *rnh; register int i; struct radix_node *rn; - struct sockaddr *saddr, *smask = 0; + struct sockaddr *saddr, *smask = NULL; #if defined(INET6) || defined(INET) int off; #endif diff --git a/sys/kern/vfs_lookup.c b/sys/kern/vfs_lookup.c index f4b0596eb233..a1116e0a522f 100644 --- a/sys/kern/vfs_lookup.c +++ b/sys/kern/vfs_lookup.c @@ -486,7 +486,7 @@ int lookup(struct nameidata *ndp) { char *cp; /* pointer into pathname argument */ - struct vnode *dp = 0; /* the directory we are searching */ + struct vnode *dp = NULL; /* the directory we are searching */ struct vnode *tdp; /* saved dp */ struct mount *mp; /* mount table entry */ struct prison *pr; @@ -949,7 +949,7 @@ lookup(struct nameidata *ndp) int relookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp) { - struct vnode *dp = 0; /* the directory we are searching */ + struct vnode *dp = NULL; /* the directory we are searching */ int wantparent; /* 1 => wantparent or lockparent flag */ int rdonly; /* lookup read-only flag bit */ int error = 0; diff --git a/sys/libkern/strtol.c b/sys/libkern/strtol.c index 4d64025dec2f..ea7dd5567285 100644 --- a/sys/libkern/strtol.c +++ b/sys/libkern/strtol.c @@ -123,7 +123,7 @@ strtol(nptr, endptr, base) acc = neg ? LONG_MIN : LONG_MAX; } else if (neg) acc = -acc; - if (endptr != 0) + if (endptr != NULL) *endptr = __DECONST(char *, any ? s - 1 : nptr); return (acc); } diff --git a/sys/libkern/strtoq.c b/sys/libkern/strtoq.c index d85505689090..e83adb1f0e35 100644 --- a/sys/libkern/strtoq.c +++ b/sys/libkern/strtoq.c @@ -124,7 +124,7 @@ strtoq(const char *nptr, char **endptr, int base) acc = neg ? QUAD_MIN : QUAD_MAX; } else if (neg) acc = -acc; - if (endptr != 0) + if (endptr != NULL) *endptr = __DECONST(char *, any ? s - 1 : nptr); return (acc); } diff --git a/sys/libkern/strtoul.c b/sys/libkern/strtoul.c index f7399dc13ef6..44adf5a30118 100644 --- a/sys/libkern/strtoul.c +++ b/sys/libkern/strtoul.c @@ -102,7 +102,7 @@ strtoul(nptr, endptr, base) acc = ULONG_MAX; } else if (neg) acc = -acc; - if (endptr != 0) + if (endptr != NULL) *endptr = __DECONST(char *, any ? s - 1 : nptr); return (acc); } diff --git a/sys/libkern/strtouq.c b/sys/libkern/strtouq.c index f8303a0d2be8..49c3750b2a8a 100644 --- a/sys/libkern/strtouq.c +++ b/sys/libkern/strtouq.c @@ -101,7 +101,7 @@ strtouq(const char *nptr, char **endptr, int base) acc = UQUAD_MAX; } else if (neg) acc = -acc; - if (endptr != 0) + if (endptr != NULL) *endptr = __DECONST(char *, any ? s - 1 : nptr); return (acc); } From 01b5c6f73e7265f62a9ce4836d22657f888121f4 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 16:18:07 +0000 Subject: [PATCH 127/143] g_gate: for pointers replace 0 with NULL. These are mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/geom/gate/g_gate.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/geom/gate/g_gate.c b/sys/geom/gate/g_gate.c index 3453eef9b783..8cfe9d4aaac0 100644 --- a/sys/geom/gate/g_gate.c +++ b/sys/geom/gate/g_gate.c @@ -945,7 +945,7 @@ g_gate_modevent(module_t mod, int type, void *data) } mtx_unlock(&g_gate_units_lock); mtx_destroy(&g_gate_units_lock); - if (status_dev != 0) + if (status_dev != NULL) destroy_dev(status_dev); free(g_gate_units, M_GATE); break; From 500ed14d6e77d0d949e27fd928d4f325d9bab0aa Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 16:21:13 +0000 Subject: [PATCH 128/143] compat/linux: for pointers replace 0 with NULL. plvc is a pointer, no functional change. Found with devel/coccinelle. --- sys/compat/linux/linux_ioctl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/compat/linux/linux_ioctl.c b/sys/compat/linux/linux_ioctl.c index 572060e8f052..bb5a475ebf03 100644 --- a/sys/compat/linux/linux_ioctl.c +++ b/sys/compat/linux/linux_ioctl.c @@ -2902,7 +2902,7 @@ linux_v4l_cliplist_copy(struct l_video_window *lvw, struct video_window *vw) vw->clips = NULL; ppvc = &(vw->clips); while (clipcount-- > 0) { - if (plvc == 0) { + if (plvc == NULL) { error = EFAULT; break; } else { From 739f4ae3b1d8f86ad86041e26afffbec4f1e2491 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Fri, 15 Apr 2016 16:36:17 +0000 Subject: [PATCH 129/143] Don't corrupt ZFS label's physpath attribute when booting while a disk is missing Prior to this change, vdev_geom_open_by_path would call vdev_geom_attach prior to verifying the device's GUIDs. vdev_geom_attach calls vdev_geom_attrchange to set the physpath in the vdev object. The result is that if the disk could not be found, then the labels for other disks in the same TLD would overwrite the missing disk's physpath with the physpath of whichever disk currently has the same devname as the missing one used to have. MFC after: 4 weeks Sponsored by: Spectra Logic Corp --- sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c index bc63fe94c6a2..a92a54bc8795 100644 --- a/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c +++ b/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev_geom.c @@ -246,9 +246,6 @@ vdev_geom_attach(struct g_provider *pp, vdev_t *vd) cp->private = vd; vd->vdev_tsd = cp; - /* Fetch initial physical path information for this device. */ - vdev_geom_attrchanged(cp, "GEOM::physpath"); - cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE; return (cp); } @@ -805,6 +802,10 @@ vdev_geom_open(vdev_t *vd, uint64_t *psize, uint64_t *max_psize, } } + /* Fetch initial physical path information for this device. */ + if (cp != NULL) + vdev_geom_attrchanged(cp, "GEOM::physpath"); + g_topology_unlock(); PICKUP_GIANT(); if (cp == NULL) { From 9f915a92c799be0097f3376d799ddbdbc5a03912 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 17:27:20 +0000 Subject: [PATCH 130/143] ddb: for pointers replace 0 with NULL. Mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/ddb/db_command.c | 4 ++-- sys/ddb/db_sym.c | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/sys/ddb/db_command.c b/sys/ddb/db_command.c index 0d4f28f8b656..4f66498f5fbc 100644 --- a/sys/ddb/db_command.c +++ b/sys/ddb/db_command.c @@ -144,7 +144,7 @@ static struct command db_cmds[] = { }; struct command_table db_cmd_table = LIST_HEAD_INITIALIZER(db_cmd_table); -static struct command *db_last_command = 0; +static struct command *db_last_command = NULL; /* * if 'ed' style: 'dot' is set at start of last item printed, @@ -429,7 +429,7 @@ db_command(struct command **last_cmdp, struct command_table *cmd_table, } } *last_cmdp = cmd; - if (cmd != 0) { + if (cmd != NULL) { /* * Execute the command. */ diff --git a/sys/ddb/db_sym.c b/sys/ddb/db_sym.c index ffcba7928476..25ae4bcaa973 100644 --- a/sys/ddb/db_sym.c +++ b/sys/ddb/db_sym.c @@ -395,7 +395,7 @@ db_symbol_values(c_db_sym_t sym, const char **namep, db_expr_t *valuep) db_expr_t value; if (sym == DB_SYM_NULL) { - *namep = 0; + *namep = NULL; return; } @@ -438,13 +438,13 @@ db_printsym(db_expr_t off, db_strategy_t strategy) cursym = db_search_symbol(off, strategy, &d); db_symbol_values(cursym, &name, &value); - if (name == 0) + if (name == NULL) value = off; if (value >= DB_SMALL_VALUE_MIN && value <= DB_SMALL_VALUE_MAX) { db_printf("%+#lr", (long)off); return; } - if (name == 0 || d >= (unsigned long)db_maxoff) { + if (name == NULL || d >= (unsigned long)db_maxoff) { db_printf("%#lr", (unsigned long)off); return; } From 0d3e502f9213fcfd816ff4075505b41e978f106f Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 17:28:24 +0000 Subject: [PATCH 131/143] fs misc: for pointers replace 0 with NULL. Mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/fs/cd9660/cd9660_vfsops.c | 4 ++-- sys/fs/msdosfs/msdosfs_conv.c | 4 ++-- sys/fs/msdosfs/msdosfs_fat.c | 4 ++-- sys/fs/msdosfs/msdosfs_lookup.c | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/sys/fs/cd9660/cd9660_vfsops.c b/sys/fs/cd9660/cd9660_vfsops.c index bf18094639ee..649b01adb83f 100644 --- a/sys/fs/cd9660/cd9660_vfsops.c +++ b/sys/fs/cd9660/cd9660_vfsops.c @@ -709,7 +709,7 @@ cd9660_vget_internal(mp, ino, flags, vpp, relocated, isodir) if (error || *vpp != NULL) return (error); - if (isodir == 0) { + if (isodir == NULL) { int lbn, off; lbn = lblkno(imp, ino); @@ -759,7 +759,7 @@ cd9660_vget_internal(mp, ino, flags, vpp, relocated, isodir) } #endif } else - bp = 0; + bp = NULL; ip->i_mnt = imp; diff --git a/sys/fs/msdosfs/msdosfs_conv.c b/sys/fs/msdosfs/msdosfs_conv.c index fc9b4d4be265..efed30ca50fc 100644 --- a/sys/fs/msdosfs/msdosfs_conv.c +++ b/sys/fs/msdosfs/msdosfs_conv.c @@ -353,7 +353,7 @@ unix2dosfn(const u_char *un, u_char dn[12], size_t unlen, u_int gen, * ignores all dots before extension, and use all * chars as filename except for dots. */ - dp = dp1 = 0; + dp = dp1 = NULL; for (cp = un + 1, i = unlen - 1; --i >= 0;) { switch (*cp++) { case '.': @@ -365,7 +365,7 @@ unix2dosfn(const u_char *un, u_char dn[12], size_t unlen, u_int gen, default: if (dp1) dp = dp1; - dp1 = 0; + dp1 = NULL; break; } } diff --git a/sys/fs/msdosfs/msdosfs_fat.c b/sys/fs/msdosfs/msdosfs_fat.c index cf03e00654e2..5df053ccdefc 100644 --- a/sys/fs/msdosfs/msdosfs_fat.c +++ b/sys/fs/msdosfs/msdosfs_fat.c @@ -256,14 +256,14 @@ fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp) { int i; u_long cn; - struct fatcache *closest = 0; + struct fatcache *closest = NULL; ASSERT_VOP_LOCKED(DETOV(dep), "fc_lookup"); for (i = 0; i < FC_SIZE; i++) { cn = dep->de_fc[i].fc_frcn; if (cn != FCE_EMPTY && cn <= findcn) { - if (closest == 0 || cn > closest->fc_frcn) + if (closest == NULL || cn > closest->fc_frcn) closest = &dep->de_fc[i]; } } diff --git a/sys/fs/msdosfs/msdosfs_lookup.c b/sys/fs/msdosfs/msdosfs_lookup.c index 0d038310f79d..f7955f20a540 100644 --- a/sys/fs/msdosfs/msdosfs_lookup.c +++ b/sys/fs/msdosfs/msdosfs_lookup.c @@ -454,7 +454,7 @@ msdosfs_lookup_(struct vnode *vdp, struct vnode **vpp, * in a deadlock. */ brelse(bp); - bp = 0; + bp = NULL; foundroot: /* From 155d72c498e67b24097e8444a289a77be6eccf85 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 17:30:33 +0000 Subject: [PATCH 132/143] sys/net* : for pointers replace 0 with NULL. Mostly cosmetical, no functional change. Found with devel/coccinelle. --- sys/net/bpf_filter.c | 8 ++++---- sys/net/if.c | 6 +++--- sys/net/if_arcsubr.c | 16 ++++++++-------- sys/net/if_atmsubr.c | 4 ++-- sys/net/if_bridge.c | 4 ++-- sys/net/if_disc.c | 2 +- sys/net/if_ethersubr.c | 4 ++-- sys/net/if_fddisubr.c | 8 ++++---- sys/net/if_fwsubr.c | 12 ++++++------ sys/net/if_iso88025subr.c | 8 ++++---- sys/net/if_loop.c | 2 +- sys/net/if_spppsubr.c | 6 +++--- sys/net/radix.c | 18 +++++++++--------- sys/net/raw_usrreq.c | 2 +- sys/netgraph/atm/ccatm/ng_ccatm.c | 2 +- sys/netgraph/ng_socket.c | 4 ++-- sys/netgraph/ng_source.c | 2 +- sys/netinet6/in6.c | 2 +- sys/netinet6/ip6_output.c | 10 +++++----- sys/netinet6/nd6_rtr.c | 2 +- sys/netinet6/raw_ip6.c | 2 +- sys/netinet6/udp6_usrreq.c | 4 ++-- sys/netipsec/ipsec_mbuf.c | 2 +- sys/netipsec/key.c | 12 ++++++------ sys/netipsec/keysock.c | 8 ++++---- sys/netipsec/xform_ipcomp.c | 2 +- 26 files changed, 76 insertions(+), 76 deletions(-) diff --git a/sys/net/bpf_filter.c b/sys/net/bpf_filter.c index 40498a9e603f..ab3198ab3ea0 100644 --- a/sys/net/bpf_filter.c +++ b/sys/net/bpf_filter.c @@ -99,7 +99,7 @@ m_xword(struct mbuf *m, bpf_u_int32 k, int *err) while (k >= len) { k -= len; m = m->m_next; - if (m == 0) + if (m == NULL) goto bad; len = m->m_len; } @@ -109,7 +109,7 @@ m_xword(struct mbuf *m, bpf_u_int32 k, int *err) return (EXTRACT_LONG(cp)); } m0 = m->m_next; - if (m0 == 0 || m0->m_len + len - k < 4) + if (m0 == NULL || m0->m_len + len - k < 4) goto bad; *err = 0; np = mtod(m0, u_char *); @@ -148,7 +148,7 @@ m_xhalf(struct mbuf *m, bpf_u_int32 k, int *err) while (k >= len) { k -= len; m = m->m_next; - if (m == 0) + if (m == NULL) goto bad; len = m->m_len; } @@ -158,7 +158,7 @@ m_xhalf(struct mbuf *m, bpf_u_int32 k, int *err) return (EXTRACT_SHORT(cp)); } m0 = m->m_next; - if (m0 == 0) + if (m0 == NULL) goto bad; *err = 0; return ((cp[0] << 8) | mtod(m0, u_char *)[0]); diff --git a/sys/net/if.c b/sys/net/if.c index 2c44c87b009d..1a110932339a 100644 --- a/sys/net/if.c +++ b/sys/net/if.c @@ -1948,8 +1948,8 @@ link_rtrequest(int cmd, struct rtentry *rt, struct rt_addrinfo *info) struct sockaddr *dst; struct ifnet *ifp; - if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == 0) || - ((ifp = ifa->ifa_ifp) == 0) || ((dst = rt_key(rt)) == 0)) + if (cmd != RTM_ADD || ((ifa = rt->rt_ifa) == NULL) || + ((ifp = ifa->ifa_ifp) == NULL) || ((dst = rt_key(rt)) == NULL)) return; ifa = ifaof_ifpforaddr(dst, ifp); if (ifa) { @@ -2139,7 +2139,7 @@ if_qflush(struct ifnet *ifp) ALTQ_PURGE(ifq); #endif n = ifq->ifq_head; - while ((m = n) != 0) { + while ((m = n) != NULL) { n = m->m_nextpkt; m_freem(m); } diff --git a/sys/net/if_arcsubr.c b/sys/net/if_arcsubr.c index 16adba4e6cbf..14026b40351e 100644 --- a/sys/net/if_arcsubr.c +++ b/sys/net/if_arcsubr.c @@ -210,7 +210,7 @@ arc_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, isphds = arc_isphds(atype); M_PREPEND(m, isphds ? ARC_HDRNEWLEN : ARC_HDRLEN, M_NOWAIT); - if (m == 0) + if (m == NULL) senderr(ENOBUFS); ah = mtod(m, struct arc_header *); ah->arc_type = atype; @@ -261,12 +261,12 @@ arc_frag_next(struct ifnet *ifp) struct arc_header *ah; ac = (struct arccom *)ifp->if_l2com; - if ((m = ac->curr_frag) == 0) { + if ((m = ac->curr_frag) == NULL) { int tfrags; /* dequeue new packet */ IF_DEQUEUE(&ifp->if_snd, m); - if (m == 0) + if (m == NULL) return 0; ah = mtod(m, struct arc_header *); @@ -296,7 +296,7 @@ arc_frag_next(struct ifnet *ifp) } M_PREPEND(m, ARC_HDRNEWLEN, M_NOWAIT); - if (m == 0) { + if (m == NULL) { m_freem(ac->curr_frag); ac->curr_frag = 0; return 0; @@ -315,7 +315,7 @@ arc_frag_next(struct ifnet *ifp) ac->curr_frag = 0; M_PREPEND(m, ARC_HDRNEWLEN_EXC, M_NOWAIT); - if (m == 0) + if (m == NULL) return 0; ah = mtod(m, struct arc_header *); @@ -328,7 +328,7 @@ arc_frag_next(struct ifnet *ifp) ac->curr_frag = 0; M_PREPEND(m, ARC_HDRNEWLEN, M_NOWAIT); - if (m == 0) + if (m == NULL) return 0; ah = mtod(m, struct arc_header *); @@ -740,7 +740,7 @@ arc_resolvemulti(struct ifnet *ifp, struct sockaddr **llsa, sdl = (struct sockaddr_dl *)sa; if (*LLADDR(sdl) != arcbroadcastaddr) return EADDRNOTAVAIL; - *llsa = 0; + *llsa = NULL; return 0; #ifdef INET case AF_INET: @@ -763,7 +763,7 @@ arc_resolvemulti(struct ifnet *ifp, struct sockaddr **llsa, * (This is used for multicast routers.) */ ifp->if_flags |= IFF_ALLMULTI; - *llsa = 0; + *llsa = NULL; return 0; } if (!IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) diff --git a/sys/net/if_atmsubr.c b/sys/net/if_atmsubr.c index e1c4a6753973..2d38b8ada7e9 100644 --- a/sys/net/if_atmsubr.c +++ b/sys/net/if_atmsubr.c @@ -192,7 +192,7 @@ atm_output(struct ifnet *ifp, struct mbuf *m0, const struct sockaddr *dst, if (atm_flags & ATM_PH_LLCSNAP) sz += 8; /* sizeof snap == 8 */ M_PREPEND(m, sz, M_NOWAIT); - if (m == 0) + if (m == NULL) senderr(ENOBUFS); ad = mtod(m, struct atm_pseudohdr *); *ad = atmdst; @@ -295,7 +295,7 @@ atm_input(struct ifnet *ifp, struct atm_pseudohdr *ah, struct mbuf *m, struct atmllc *alc; if (m->m_len < sizeof(*alc) && - (m = m_pullup(m, sizeof(*alc))) == 0) + (m = m_pullup(m, sizeof(*alc))) == NULL) return; /* failed */ alc = mtod(m, struct atmllc *); if (bcmp(alc, ATMLLC_HDR, 6)) { diff --git a/sys/net/if_bridge.c b/sys/net/if_bridge.c index c6bcfdf80fe0..6b037117ab93 100644 --- a/sys/net/if_bridge.c +++ b/sys/net/if_bridge.c @@ -3248,7 +3248,7 @@ bridge_pfil(struct mbuf **mp, struct ifnet *bifp, struct ifnet *ifp, int dir) if (hlen < sizeof(struct ip)) goto bad; if (hlen > (*mp)->m_len) { - if ((*mp = m_pullup(*mp, hlen)) == 0) + if ((*mp = m_pullup(*mp, hlen)) == NULL) goto bad; ip = mtod(*mp, struct ip *); if (ip == NULL) @@ -3366,7 +3366,7 @@ bridge_ip_checkbasic(struct mbuf **mp) goto bad; } if (hlen > m->m_len) { - if ((m = m_pullup(m, hlen)) == 0) { + if ((m = m_pullup(m, hlen)) == NULL) { KMOD_IPSTAT_INC(ips_badhlen); goto bad; } diff --git a/sys/net/if_disc.c b/sys/net/if_disc.c index b6e1d203d214..d7ea59ed426f 100644 --- a/sys/net/if_disc.c +++ b/sys/net/if_disc.c @@ -216,7 +216,7 @@ discioctl(struct ifnet *ifp, u_long cmd, caddr_t data) break; case SIOCADDMULTI: case SIOCDELMULTI: - if (ifr == 0) { + if (ifr == NULL) { error = EAFNOSUPPORT; /* XXX */ break; } diff --git a/sys/net/if_ethersubr.c b/sys/net/if_ethersubr.c index 2d652ad8fc31..8698647a8603 100644 --- a/sys/net/if_ethersubr.c +++ b/sys/net/if_ethersubr.c @@ -1075,7 +1075,7 @@ ether_resolvemulti(struct ifnet *ifp, struct sockaddr **llsa, e_addr = LLADDR(sdl); if (!ETHER_IS_MULTICAST(e_addr)) return EADDRNOTAVAIL; - *llsa = 0; + *llsa = NULL; return 0; #ifdef INET @@ -1100,7 +1100,7 @@ ether_resolvemulti(struct ifnet *ifp, struct sockaddr **llsa, * (This is used for multicast routers.) */ ifp->if_flags |= IFF_ALLMULTI; - *llsa = 0; + *llsa = NULL; return 0; } if (!IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) diff --git a/sys/net/if_fddisubr.c b/sys/net/if_fddisubr.c index 84ee669ae254..1ebd4da44d6f 100644 --- a/sys/net/if_fddisubr.c +++ b/sys/net/if_fddisubr.c @@ -235,7 +235,7 @@ fddi_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, if (type != 0) { struct llc *l; M_PREPEND(m, LLC_SNAPFRAMELEN, M_NOWAIT); - if (m == 0) + if (m == NULL) senderr(ENOBUFS); l = mtod(m, struct llc *); l->llc_control = LLC_UI; @@ -251,7 +251,7 @@ fddi_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, * allocate another. */ M_PREPEND(m, FDDI_HDR_LEN, M_NOWAIT); - if (m == 0) + if (m == NULL) senderr(ENOBUFS); fh = mtod(m, struct fddi_header *); fh->fddi_fc = FDDIFC_LLC_ASYNC|FDDIFC_LLC_PRIO4; @@ -607,7 +607,7 @@ fddi_resolvemulti(ifp, llsa, sa) e_addr = LLADDR(sdl); if ((e_addr[0] & 1) != 1) return (EADDRNOTAVAIL); - *llsa = 0; + *llsa = NULL; return (0); #ifdef INET @@ -634,7 +634,7 @@ fddi_resolvemulti(ifp, llsa, sa) * (This is used for multicast routers.) */ ifp->if_flags |= IFF_ALLMULTI; - *llsa = 0; + *llsa = NULL; return (0); } if (!IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) diff --git a/sys/net/if_fwsubr.c b/sys/net/if_fwsubr.c index a070f6176023..c2253d4ef0ae 100644 --- a/sys/net/if_fwsubr.c +++ b/sys/net/if_fwsubr.c @@ -132,7 +132,7 @@ firewire_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, } destfw = (struct fw_hwaddr *)(mtag + 1); } else { - destfw = 0; + destfw = NULL; } switch (dst->sa_family) { @@ -269,7 +269,7 @@ firewire_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, mtail = m_split(m, fsize, M_NOWAIT); m_tag_copy_chain(mtail, m, M_NOWAIT); } else { - mtail = 0; + mtail = NULL; } /* @@ -701,7 +701,7 @@ firewire_resolvemulti(struct ifnet *ifp, struct sockaddr **llsa, /* * No mapping needed. */ - *llsa = 0; + *llsa = NULL; return 0; #ifdef INET @@ -709,7 +709,7 @@ firewire_resolvemulti(struct ifnet *ifp, struct sockaddr **llsa, sin = (struct sockaddr_in *)sa; if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) return EADDRNOTAVAIL; - *llsa = 0; + *llsa = NULL; return 0; #endif #ifdef INET6 @@ -722,12 +722,12 @@ firewire_resolvemulti(struct ifnet *ifp, struct sockaddr **llsa, * (This is used for multicast routers.) */ ifp->if_flags |= IFF_ALLMULTI; - *llsa = 0; + *llsa = NULL; return 0; } if (!IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) return EADDRNOTAVAIL; - *llsa = 0; + *llsa = NULL; return 0; #endif diff --git a/sys/net/if_iso88025subr.c b/sys/net/if_iso88025subr.c index 466784fb075f..a96e2b9c6946 100644 --- a/sys/net/if_iso88025subr.c +++ b/sys/net/if_iso88025subr.c @@ -328,7 +328,7 @@ iso88025_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, if (snap_type != 0) { struct llc *l; M_PREPEND(m, LLC_SNAPFRAMELEN, M_NOWAIT); - if (m == 0) + if (m == NULL) senderr(ENOBUFS); l = mtod(m, struct llc *); l->llc_control = LLC_UI; @@ -344,7 +344,7 @@ iso88025_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst, * allocate another. */ M_PREPEND(m, ISO88025_HDR_LEN + rif_len, M_NOWAIT); - if (m == 0) + if (m == NULL) senderr(ENOBUFS); th = mtod(m, struct iso88025_header *); bcopy((caddr_t)edst, (caddr_t)&gen_th.iso88025_dhost, ISO88025_ADDR_LEN); @@ -638,7 +638,7 @@ iso88025_resolvemulti (ifp, llsa, sa) if ((e_addr[0] & 1) != 1) { return (EADDRNOTAVAIL); } - *llsa = 0; + *llsa = NULL; return (0); #ifdef INET @@ -664,7 +664,7 @@ iso88025_resolvemulti (ifp, llsa, sa) * (This is used for multicast routers.) */ ifp->if_flags |= IFF_ALLMULTI; - *llsa = 0; + *llsa = NULL; return (0); } if (!IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) { diff --git a/sys/net/if_loop.c b/sys/net/if_loop.c index 1291f7b44d91..1623732ee420 100644 --- a/sys/net/if_loop.c +++ b/sys/net/if_loop.c @@ -380,7 +380,7 @@ loioctl(struct ifnet *ifp, u_long cmd, caddr_t data) case SIOCADDMULTI: case SIOCDELMULTI: - if (ifr == 0) { + if (ifr == NULL) { error = EAFNOSUPPORT; /* XXX */ break; } diff --git a/sys/net/if_spppsubr.c b/sys/net/if_spppsubr.c index 841a0f20741e..092106e49d9d 100644 --- a/sys/net/if_spppsubr.c +++ b/sys/net/if_spppsubr.c @@ -4835,7 +4835,7 @@ sppp_get_ip_addrs(struct sppp *sp, u_long *src, u_long *dst, u_long *srcmask) * Pick the first AF_INET address from the list, * aliases don't make any sense on a p2p link anyway. */ - si = 0; + si = NULL; if_addr_rlock(ifp); TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) if (ifa->ifa_addr->sa_family == AF_INET) { @@ -4877,7 +4877,7 @@ sppp_set_ip_addr(struct sppp *sp, u_long src) * Pick the first AF_INET address from the list, * aliases don't make any sense on a p2p link anyway. */ - si = 0; + si = NULL; if_addr_rlock(ifp); TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) { if (ifa->ifa_addr->sa_family == AF_INET) { @@ -5055,7 +5055,7 @@ sppp_params(struct sppp *sp, u_long cmd, void *data) struct spppreq *spr; int rv = 0; - if ((spr = malloc(sizeof(struct spppreq), M_TEMP, M_NOWAIT)) == 0) + if ((spr = malloc(sizeof(struct spppreq), M_TEMP, M_NOWAIT)) == NULL) return (EAGAIN); /* * ifr->ifr_data is supposed to point to a struct spppreq. diff --git a/sys/net/radix.c b/sys/net/radix.c index 2b4b9542b58f..b17858e4a016 100644 --- a/sys/net/radix.c +++ b/sys/net/radix.c @@ -519,11 +519,11 @@ rn_addmask(void *n_arg, struct radix_mask_head *maskhead, int search, int skip) *addmask_key = mlen; x = rn_search(addmask_key, maskhead->head.rnh_treetop); if (bcmp(addmask_key, x->rn_key, mlen) != 0) - x = 0; + x = NULL; if (x || search) return (x); R_Zalloc(x, struct radix_node *, RADIX_MAX_KEY_LEN + 2 * sizeof (*x)); - if ((saved_x = x) == 0) + if ((saved_x = x) == NULL) return (0); netmask = cp = (unsigned char *)(x + 2); bcopy(addmask_key, cp, mlen); @@ -599,7 +599,7 @@ rn_addroute(void *v_arg, void *n_arg, struct radix_head *head, struct radix_node treenodes[2]) { caddr_t v = (caddr_t)v_arg, netmask = (caddr_t)n_arg; - struct radix_node *t, *x = 0, *tt; + struct radix_node *t, *x = NULL, *tt; struct radix_node *saved_tt, *top = head->rnh_treetop; short b = 0, b_leaf = 0; int keyduplicated; @@ -722,7 +722,7 @@ rn_addroute(void *v_arg, void *n_arg, struct radix_head *head, for (mp = &x->rn_mklist; (m = *mp); mp = &m->rm_mklist) if (m->rm_bit >= b_leaf) break; - t->rn_mklist = m; *mp = 0; + t->rn_mklist = m; *mp = NULL; } on2: /* Add new route to highest possible ancestor's list */ @@ -785,7 +785,7 @@ rn_delete(void *v_arg, void *netmask_arg, struct radix_head *head) vlen = LEN(v); saved_tt = tt; top = x; - if (tt == 0 || + if (tt == NULL || bcmp(v + head_off, tt->rn_key + head_off, vlen - head_off)) return (0); /* @@ -797,10 +797,10 @@ rn_delete(void *v_arg, void *netmask_arg, struct radix_head *head) return (0); netmask = x->rn_key; while (tt->rn_mask != netmask) - if ((tt = tt->rn_dupedkey) == 0) + if ((tt = tt->rn_dupedkey) == NULL) return (0); } - if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == 0) + if (tt->rn_mask == 0 || (saved_m = m = tt->rn_mklist) == NULL) goto on1; if (tt->rn_flags & RNF_NORMAL) { if (m->rm_leaf != tt || m->rm_refs > 0) { @@ -829,7 +829,7 @@ rn_delete(void *v_arg, void *netmask_arg, struct radix_head *head) R_Free(m); break; } - if (m == 0) { + if (m == NULL) { log(LOG_ERR, "rn_delete: couldn't find our annotation\n"); if (tt->rn_flags & RNF_NORMAL) return (0); /* Dangling ref to us */ @@ -1044,7 +1044,7 @@ rn_walktree_from(struct radix_head *h, void *a, void *m, rn = rn->rn_left; next = rn; /* Process leaves */ - while ((rn = base) != 0) { + while ((rn = base) != NULL) { base = rn->rn_dupedkey; /* printf("leaf %p\n", rn); */ if (!(rn->rn_flags & RNF_ROOT) diff --git a/sys/net/raw_usrreq.c b/sys/net/raw_usrreq.c index 87bcd895a477..9e22528b7e98 100644 --- a/sys/net/raw_usrreq.c +++ b/sys/net/raw_usrreq.c @@ -83,7 +83,7 @@ raw_input_ext(struct mbuf *m0, struct sockproto *proto, struct sockaddr *src, struct mbuf *m = m0; struct socket *last; - last = 0; + last = NULL; mtx_lock(&rawcb_mtx); LIST_FOREACH(rp, &V_rawcb_list, list) { if (rp->rcb_proto.sp_family != proto->sp_family) diff --git a/sys/netgraph/atm/ccatm/ng_ccatm.c b/sys/netgraph/atm/ccatm/ng_ccatm.c index cdbc86f86331..cc3f7519289f 100644 --- a/sys/netgraph/atm/ccatm/ng_ccatm.c +++ b/sys/netgraph/atm/ccatm/ng_ccatm.c @@ -441,7 +441,7 @@ send_dump(struct ccdata *data, void *uarg, const char *buf) m->m_pkthdr.len = 0; } else { m = m_getcl(M_NOWAIT, MT_DATA, 0); - if (m == 0) { + if (m == NULL) { m_freem(priv->dump_first); return (ENOBUFS); } diff --git a/sys/netgraph/ng_socket.c b/sys/netgraph/ng_socket.c index 38da313b836a..76d6383f0fb8 100644 --- a/sys/netgraph/ng_socket.c +++ b/sys/netgraph/ng_socket.c @@ -360,7 +360,7 @@ ngc_bind(struct socket *so, struct sockaddr *nam, struct thread *td) { struct ngpcb *const pcbp = sotongpcb(so); - if (pcbp == 0) + if (pcbp == NULL) return (EINVAL); return (ng_bind(nam, pcbp)); } @@ -474,7 +474,7 @@ ngd_connect(struct socket *so, struct sockaddr *nam, struct thread *td) { struct ngpcb *const pcbp = sotongpcb(so); - if (pcbp == 0) + if (pcbp == NULL) return (EINVAL); return (ng_connect_data(nam, pcbp)); } diff --git a/sys/netgraph/ng_source.c b/sys/netgraph/ng_source.c index 1883ec021ac3..8332d20f9f28 100644 --- a/sys/netgraph/ng_source.c +++ b/sys/netgraph/ng_source.c @@ -294,7 +294,7 @@ ng_source_newhook(node_p node, hook_p hook, const char *name) sc->input = hook; } else if (strcmp(name, NG_SOURCE_HOOK_OUTPUT) == 0) { sc->output = hook; - sc->output_ifp = 0; + sc->output_ifp = NULL; bzero(&sc->stats, sizeof(sc->stats)); } else return (EINVAL); diff --git a/sys/netinet6/in6.c b/sys/netinet6/in6.c index 797093a5be1d..48f05e73fbaa 100644 --- a/sys/netinet6/in6.c +++ b/sys/netinet6/in6.c @@ -1823,7 +1823,7 @@ in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst) { int dst_scope = in6_addrscope(dst), blen = -1, tlen; struct ifaddr *ifa; - struct in6_ifaddr *besta = 0; + struct in6_ifaddr *besta = NULL; struct in6_ifaddr *dep[2]; /* last-resort: deprecated */ dep[0] = dep[1] = NULL; diff --git a/sys/netinet6/ip6_output.c b/sys/netinet6/ip6_output.c index 7895139c6b85..f64d305f626a 100644 --- a/sys/netinet6/ip6_output.c +++ b/sys/netinet6/ip6_output.c @@ -256,7 +256,7 @@ ip6_fragment(struct ifnet *ifp, struct mbuf *m0, int hlen, u_char nextproto, ip6f->ip6f_offlg |= IP6F_MORE_FRAG; mhip6->ip6_plen = htons((u_short)(mtu + hlen + sizeof(*ip6f) - sizeof(struct ip6_hdr))); - if ((m_frgpart = m_copy(m0, off, mtu)) == 0) { + if ((m_frgpart = m_copy(m0, off, mtu)) == NULL) { IP6STAT_INC(ip6s_odropped); return (ENOBUFS); } @@ -503,7 +503,7 @@ ip6_output(struct mbuf *m0, struct ip6_pktopts *opt, /* * Route packet. */ - if (ro == 0) { + if (ro == NULL) { ro = &ip6route; bzero((caddr_t)ro, sizeof(*ro)); } @@ -1116,7 +1116,7 @@ ip6_insert_jumboopt(struct ip6_exthdrs *exthdrs, u_int32_t plen) * jumbo payload option, allocate a cluster to store the whole options. * Otherwise, use it to store the options. */ - if (exthdrs->ip6e_hbh == 0) { + if (exthdrs->ip6e_hbh == NULL) { mopt = m_get(M_NOWAIT, MT_DATA); if (mopt == NULL) return (ENOBUFS); @@ -1198,7 +1198,7 @@ ip6_insertfraghdr(struct mbuf *m0, struct mbuf *m, int hlen, if (hlen > sizeof(struct ip6_hdr)) { n = m_copym(m0, sizeof(struct ip6_hdr), hlen - sizeof(struct ip6_hdr), M_NOWAIT); - if (n == 0) + if (n == NULL) return (ENOBUFS); m->m_next = n; } else @@ -2515,7 +2515,7 @@ int ip6_setpktopts(struct mbuf *control, struct ip6_pktopts *opt, struct ip6_pktopts *stickyopt, struct ucred *cred, int uproto) { - struct cmsghdr *cm = 0; + struct cmsghdr *cm = NULL; if (control == NULL || opt == NULL) return (EINVAL); diff --git a/sys/netinet6/nd6_rtr.c b/sys/netinet6/nd6_rtr.c index 6fee83013ff5..aa7baad85402 100644 --- a/sys/netinet6/nd6_rtr.c +++ b/sys/netinet6/nd6_rtr.c @@ -1510,7 +1510,7 @@ pfxlist_onlink_check() find_pfxlist_reachable_router(pr) == NULL) pr->ndpr_stateflags |= NDPRF_DETACHED; if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 && - find_pfxlist_reachable_router(pr) != 0) + find_pfxlist_reachable_router(pr) != NULL) pr->ndpr_stateflags &= ~NDPRF_DETACHED; } } else { diff --git a/sys/netinet6/raw_ip6.c b/sys/netinet6/raw_ip6.c index 972eb9f1d9ee..2b95e4811fec 100644 --- a/sys/netinet6/raw_ip6.c +++ b/sys/netinet6/raw_ip6.c @@ -163,7 +163,7 @@ rip6_input(struct mbuf **mp, int *offp, int proto) struct mbuf *m = *mp; register struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *); register struct inpcb *in6p; - struct inpcb *last = 0; + struct inpcb *last = NULL; struct mbuf *opts = NULL; struct sockaddr_in6 fromsa; diff --git a/sys/netinet6/udp6_usrreq.c b/sys/netinet6/udp6_usrreq.c index ebcf6d6738b9..03479fdbdb40 100644 --- a/sys/netinet6/udp6_usrreq.c +++ b/sys/netinet6/udp6_usrreq.c @@ -1212,9 +1212,9 @@ udp6_send(struct socket *so, int flags, struct mbuf *m, #ifdef INET if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) { int hasv4addr; - struct sockaddr_in6 *sin6 = 0; + struct sockaddr_in6 *sin6 = NULL; - if (addr == 0) + if (addr == NULL) hasv4addr = (inp->inp_vflag & INP_IPV4); else { sin6 = (struct sockaddr_in6 *)addr; diff --git a/sys/netipsec/ipsec_mbuf.c b/sys/netipsec/ipsec_mbuf.c index b3df0e01cc50..7111210d1159 100644 --- a/sys/netipsec/ipsec_mbuf.c +++ b/sys/netipsec/ipsec_mbuf.c @@ -202,7 +202,7 @@ m_pad(struct mbuf *m, int n) if (pad > M_TRAILINGSPACE(m0)) { /* Add an mbuf to the chain. */ MGET(m1, M_NOWAIT, MT_DATA); - if (m1 == 0) { + if (m1 == NULL) { m_freem(m0); DPRINTF(("%s: unable to get extra mbuf\n", __func__)); return NULL; diff --git a/sys/netipsec/key.c b/sys/netipsec/key.c index 865a63084bcc..7070c1df4510 100644 --- a/sys/netipsec/key.c +++ b/sys/netipsec/key.c @@ -4923,8 +4923,8 @@ key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) dport = (struct sadb_x_nat_t_port *) mhp->ext[SADB_X_EXT_NAT_T_DPORT]; } else { - type = 0; - sport = dport = 0; + type = NULL; + sport = dport = NULL; } if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL && mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) { @@ -4949,7 +4949,7 @@ key_update(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) frag = (struct sadb_x_nat_t_frag *) mhp->ext[SADB_X_EXT_NAT_T_FRAG]; } else { - frag = 0; + frag = NULL; } #endif @@ -5215,7 +5215,7 @@ key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) KEY_PORTTOSADDR(&saidx.dst, dport->sadb_x_nat_t_port_port); } else { - type = 0; + type = NULL; } if (mhp->ext[SADB_X_EXT_NAT_T_OAI] != NULL && mhp->ext[SADB_X_EXT_NAT_T_OAR] != NULL) { @@ -5240,7 +5240,7 @@ key_add(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) frag = (struct sadb_x_nat_t_frag *) mhp->ext[SADB_X_EXT_NAT_T_FRAG]; } else { - frag = 0; + frag = NULL; } #endif @@ -6599,7 +6599,7 @@ key_acquire2(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) static int key_register(struct socket *so, struct mbuf *m, const struct sadb_msghdr *mhp) { - struct secreg *reg, *newreg = 0; + struct secreg *reg, *newreg = NULL; IPSEC_ASSERT(so != NULL, ("null socket")); IPSEC_ASSERT(m != NULL, ("null mbuf")); diff --git a/sys/netipsec/keysock.c b/sys/netipsec/keysock.c index 4d1295764b6e..73e54bb3de32 100644 --- a/sys/netipsec/keysock.c +++ b/sys/netipsec/keysock.c @@ -92,7 +92,7 @@ key_output(struct mbuf *m, struct socket *so, ...) struct sadb_msg *msg; int len, error = 0; - if (m == 0) + if (m == NULL) panic("%s: NULL pointer was passed.\n", __func__); PFKEYSTAT_INC(out_total); @@ -106,7 +106,7 @@ key_output(struct mbuf *m, struct socket *so, ...) } if (m->m_len < sizeof(struct sadb_msg)) { - if ((m = m_pullup(m, sizeof(struct sadb_msg))) == 0) { + if ((m = m_pullup(m, sizeof(struct sadb_msg))) == NULL) { PFKEYSTAT_INC(out_nomem); error = ENOBUFS; goto end; @@ -178,7 +178,7 @@ key_sendup(struct socket *so, struct sadb_msg *msg, u_int len, int target) int tlen; /* sanity check */ - if (so == 0 || msg == 0) + if (so == NULL || msg == NULL) panic("%s: NULL pointer was passed.\n", __func__); KEYDEBUG(KEYDEBUG_KEY_DUMP, @@ -388,7 +388,7 @@ key_attach(struct socket *so, int proto, struct thread *td) /* XXX */ kp = malloc(sizeof *kp, M_PCB, M_WAITOK | M_ZERO); - if (kp == 0) + if (kp == NULL) return ENOBUFS; so->so_pcb = (caddr_t)kp; diff --git a/sys/netipsec/xform_ipcomp.c b/sys/netipsec/xform_ipcomp.c index 122fc7261378..ae19d8d05e64 100644 --- a/sys/netipsec/xform_ipcomp.c +++ b/sys/netipsec/xform_ipcomp.c @@ -283,7 +283,7 @@ ipcomp_input_cb(struct cryptop *crp) /* In case it's not done already, adjust the size of the mbuf chain */ m->m_pkthdr.len = clen + hlen + skip; - if (m->m_len < skip + hlen && (m = m_pullup(m, skip + hlen)) == 0) { + if (m->m_len < skip + hlen && (m = m_pullup(m, skip + hlen)) == NULL) { IPCOMPSTAT_INC(ipcomps_hdrops); /*XXX*/ DPRINTF(("%s: m_pullup failed\n", __func__)); error = EINVAL; /*XXX*/ From 5dc5dab6eb40126ad56224fb2edbac445ed38f52 Mon Sep 17 00:00:00 2001 From: Conrad Meyer Date: Fri, 15 Apr 2016 17:45:12 +0000 Subject: [PATCH 133/143] Add 4Kn kernel dump support (And 4Kn minidump support, but only for amd64.) Make sure all I/O to the dump device is of the native sector size. To that end, we keep a native sector sized buffer associated with dump devices (di->blockbuf) and use it to pad smaller objects as needed (e.g. kerneldumpheader). Add dump_write_pad() as a convenience API to dump smaller objects with zero padding. (Rather than pull in NPM leftpad, we wrote our own.) Savecore(1) has been updated to deal with these dumps. The format for 512-byte sector dumps should remain backwards compatible. Minidumps for other architectures are left as an exercise for the reader. PR: 194279 Submitted by: ambrisko@ Reviewed by: cem (earlier version), rpokala Tested by: rpokala (4Kn/512 except 512 fulldump), cem (512 fulldump) Relnotes: yes Sponsored by: EMC / Isilon Storage Division Differential Revision: https://reviews.freebsd.org/D5848 --- sbin/savecore/savecore.c | 33 ++++++++++++++++++++++------- sys/amd64/amd64/minidump_machdep.c | 16 ++++++-------- sys/kern/kern_dump.c | 34 ++++++++++++++---------------- sys/kern/kern_shutdown.c | 32 +++++++++++++++++++++++++++- sys/sys/conf.h | 11 ++++++---- 5 files changed, 86 insertions(+), 40 deletions(-) diff --git a/sbin/savecore/savecore.c b/sbin/savecore/savecore.c index 7809c58d579d..63f4ef26e5db 100644 --- a/sbin/savecore/savecore.c +++ b/sbin/savecore/savecore.c @@ -436,7 +436,7 @@ DoFile(const char *savedir, const char *device) { xo_handle_t *xostdout, *xoinfo; static char infoname[PATH_MAX], corename[PATH_MAX], linkname[PATH_MAX]; - static char *buf = NULL; + static char *buf = NULL, *temp = NULL; struct kerneldumpheader kdhf, kdhl; off_t mediasize, dumpsize, firsthd, lasthd; FILE *info, *fp; @@ -490,14 +490,29 @@ DoFile(const char *savedir, const char *device) printf("sectorsize = %u\n", sectorsize); } + if (sectorsize < sizeof(kdhl)) { + syslog(LOG_ERR, + "Sector size is less the kernel dump header %zu", + sizeof(kdhl)); + goto closefd; + } + lasthd = mediasize - sectorsize; + if (temp == NULL) { + temp = malloc(sectorsize); + if (temp == NULL) { + syslog(LOG_ERR, "%m"); + return; + } + } if (lseek(fd, lasthd, SEEK_SET) != lasthd || - read(fd, &kdhl, sizeof(kdhl)) != sizeof(kdhl)) { + read(fd, temp, sectorsize) != sectorsize) { syslog(LOG_ERR, "error reading last dump header at offset %lld in %s: %m", (long long)lasthd, device); goto closefd; } + memcpy(&kdhl, temp, sizeof(kdhl)); istextdump = 0; if (strncmp(kdhl.magic, TEXTDUMPMAGIC, sizeof kdhl) == 0) { if (verbose) @@ -567,15 +582,16 @@ DoFile(const char *savedir, const char *device) goto closefd; } dumpsize = dtoh64(kdhl.dumplength); - firsthd = lasthd - dumpsize - sizeof kdhf; + firsthd = lasthd - dumpsize - sectorsize; if (lseek(fd, firsthd, SEEK_SET) != firsthd || - read(fd, &kdhf, sizeof(kdhf)) != sizeof(kdhf)) { + read(fd, temp, sectorsize) != sectorsize) { syslog(LOG_ERR, "error reading first dump header at offset %lld in %s: %m", (long long)firsthd, device); nerr++; goto closefd; } + memcpy(&kdhf, temp, sizeof(kdhf)); if (verbose >= 2) { printf("First dump headers:\n"); @@ -586,7 +602,7 @@ DoFile(const char *savedir, const char *device) printf("\n"); } - if (memcmp(&kdhl, &kdhf, sizeof kdhl)) { + if (memcmp(&kdhl, &kdhf, sizeof(kdhl))) { syslog(LOG_ERR, "first and last dump headers disagree on %s", device); nerr++; @@ -603,7 +619,7 @@ DoFile(const char *savedir, const char *device) exit(0); } - if (kdhl.panicstring[0]) + if (kdhl.panicstring[0] != '\0') syslog(LOG_ALERT, "reboot after panic: %*s", (int)sizeof(kdhl.panicstring), kdhl.panicstring); else @@ -724,9 +740,10 @@ DoFile(const char *savedir, const char *device) if (!keep) { if (verbose) printf("clearing dump header\n"); - memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof kdhl.magic); + memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic)); + memcpy(temp, &kdhl, sizeof(kdhl)); if (lseek(fd, lasthd, SEEK_SET) != lasthd || - write(fd, &kdhl, sizeof(kdhl)) != sizeof(kdhl)) + write(fd, temp, sectorsize) != sectorsize) syslog(LOG_ERR, "error while clearing the dump header: %m"); } diff --git a/sys/amd64/amd64/minidump_machdep.c b/sys/amd64/amd64/minidump_machdep.c index cc32cdc21007..df04f425100c 100644 --- a/sys/amd64/amd64/minidump_machdep.c +++ b/sys/amd64/amd64/minidump_machdep.c @@ -56,9 +56,6 @@ CTASSERT(sizeof(struct kerneldumpheader) == 512); */ #define SIZEOF_METADATA (64*1024) -#define MD_ALIGN(x) (((off_t)(x) + PAGE_MASK) & ~PAGE_MASK) -#define DEV_ALIGN(x) (((off_t)(x) + (DEV_BSIZE-1)) & ~(DEV_BSIZE-1)) - uint64_t *vm_page_dump; int vm_page_dump_size; @@ -222,6 +219,7 @@ minidumpsys(struct dumperinfo *di) int error; uint64_t bits; uint64_t *pml4, *pdp, *pd, *pt, pa; + size_t size; int i, ii, j, k, n, bit; int retry_count; struct minidumphdr mdhdr; @@ -319,12 +317,12 @@ minidumpsys(struct dumperinfo *di) dumpsize += PAGE_SIZE; /* Determine dump offset on device. */ - if (di->mediasize < SIZEOF_METADATA + dumpsize + sizeof(kdh) * 2) { + if (di->mediasize < SIZEOF_METADATA + dumpsize + di->blocksize * 2) { error = E2BIG; goto fail; } dumplo = di->mediaoffset + di->mediasize - dumpsize; - dumplo -= sizeof(kdh) * 2; + dumplo -= di->blocksize * 2; progress = dumpsize; /* Initialize mdhdr */ @@ -344,10 +342,10 @@ minidumpsys(struct dumperinfo *di) ptoa((uintmax_t)physmem) / 1048576); /* Dump leader */ - error = dump_write(di, &kdh, 0, dumplo, sizeof(kdh)); + error = dump_write_pad(di, &kdh, 0, dumplo, sizeof(kdh), &size); if (error) goto fail; - dumplo += sizeof(kdh); + dumplo += size; /* Dump my header */ bzero(&fakepd, sizeof(fakepd)); @@ -432,10 +430,10 @@ minidumpsys(struct dumperinfo *di) goto fail; /* Dump trailer */ - error = dump_write(di, &kdh, 0, dumplo, sizeof(kdh)); + error = dump_write_pad(di, &kdh, 0, dumplo, sizeof(kdh), &size); if (error) goto fail; - dumplo += sizeof(kdh); + dumplo += size; /* Signal completion, signoff and exit stage left. */ dump_write(di, NULL, 0, 0, 0); diff --git a/sys/kern/kern_dump.c b/sys/kern/kern_dump.c index c82272f09f71..e3d338fd4e29 100644 --- a/sys/kern/kern_dump.c +++ b/sys/kern/kern_dump.c @@ -55,13 +55,11 @@ CTASSERT(sizeof(struct kerneldumpheader) == 512); */ #define SIZEOF_METADATA (64*1024) -#define MD_ALIGN(x) (((off_t)(x) + PAGE_MASK) & ~PAGE_MASK) -#define DEV_ALIGN(x) (((off_t)(x) + (DEV_BSIZE-1)) & ~(DEV_BSIZE-1)) +#define MD_ALIGN(x) roundup2((off_t)(x), PAGE_SIZE) off_t dumplo; /* Handle buffered writes. */ -static char buffer[DEV_BSIZE]; static size_t fragsz; struct dump_pa dump_map[DUMPSYS_MD_PA_NPAIRS]; @@ -125,19 +123,19 @@ dumpsys_buf_write(struct dumperinfo *di, char *ptr, size_t sz) int error; while (sz) { - len = DEV_BSIZE - fragsz; + len = di->blocksize - fragsz; if (len > sz) len = sz; - bcopy(ptr, buffer + fragsz, len); + memcpy((char *)di->blockbuf + fragsz, ptr, len); fragsz += len; ptr += len; sz -= len; - if (fragsz == DEV_BSIZE) { - error = dump_write(di, buffer, 0, dumplo, - DEV_BSIZE); + if (fragsz == di->blocksize) { + error = dump_write(di, di->blockbuf, 0, dumplo, + di->blocksize); if (error) return (error); - dumplo += DEV_BSIZE; + dumplo += di->blocksize; fragsz = 0; } } @@ -152,8 +150,8 @@ dumpsys_buf_flush(struct dumperinfo *di) if (fragsz == 0) return (0); - error = dump_write(di, buffer, 0, dumplo, DEV_BSIZE); - dumplo += DEV_BSIZE; + error = dump_write(di, di->blockbuf, 0, dumplo, di->blocksize); + dumplo += di->blocksize; fragsz = 0; return (error); } @@ -286,7 +284,7 @@ dumpsys_generic(struct dumperinfo *di) Elf_Ehdr ehdr; uint64_t dumpsize; off_t hdrgap; - size_t hdrsz; + size_t hdrsz, size; int error; #ifndef __powerpc__ @@ -324,15 +322,15 @@ dumpsys_generic(struct dumperinfo *di) hdrsz = ehdr.e_phoff + ehdr.e_phnum * ehdr.e_phentsize; fileofs = MD_ALIGN(hdrsz); dumpsize += fileofs; - hdrgap = fileofs - DEV_ALIGN(hdrsz); + hdrgap = fileofs - roundup2((off_t)hdrsz, di->blocksize); /* Determine dump offset on device. */ - if (di->mediasize < SIZEOF_METADATA + dumpsize + sizeof(kdh) * 2) { + if (di->mediasize < SIZEOF_METADATA + dumpsize + di->blocksize * 2) { error = ENOSPC; goto fail; } dumplo = di->mediaoffset + di->mediasize - dumpsize; - dumplo -= sizeof(kdh) * 2; + dumplo -= di->blocksize * 2; mkdumpheader(&kdh, KERNELDUMPMAGIC, KERNELDUMP_ARCH_VERSION, dumpsize, di->blocksize); @@ -341,10 +339,10 @@ dumpsys_generic(struct dumperinfo *di) ehdr.e_phnum - DUMPSYS_NUM_AUX_HDRS); /* Dump leader */ - error = dump_write(di, &kdh, 0, dumplo, sizeof(kdh)); + error = dump_write_pad(di, &kdh, 0, dumplo, sizeof(kdh), &size); if (error) goto fail; - dumplo += sizeof(kdh); + dumplo += size; /* Dump ELF header */ error = dumpsys_buf_write(di, (char*)&ehdr, sizeof(ehdr)); @@ -375,7 +373,7 @@ dumpsys_generic(struct dumperinfo *di) goto fail; /* Dump trailer */ - error = dump_write(di, &kdh, 0, dumplo, sizeof(kdh)); + error = dump_write_pad(di, &kdh, 0, dumplo, sizeof(kdh), &size); if (error) goto fail; diff --git a/sys/kern/kern_shutdown.c b/sys/kern/kern_shutdown.c index 87e7d6388a71..7588d4c0301f 100644 --- a/sys/kern/kern_shutdown.c +++ b/sys/kern/kern_shutdown.c @@ -88,6 +88,8 @@ __FBSDID("$FreeBSD$"); #include +static MALLOC_DEFINE(M_DUMPER, "dumper", "dumper block buffer"); + #ifndef PANIC_REBOOT_WAIT_TIME #define PANIC_REBOOT_WAIT_TIME 15 /* default to 15 seconds */ #endif @@ -848,7 +850,9 @@ set_dumper(struct dumperinfo *di, const char *devname, struct thread *td) return (error); if (di == NULL) { - bzero(&dumper, sizeof dumper); + if (dumper.blockbuf != NULL) + free(dumper.blockbuf, M_DUMPER); + bzero(&dumper, sizeof(dumper)); dumpdevname[0] = '\0'; return (0); } @@ -860,6 +864,7 @@ set_dumper(struct dumperinfo *di, const char *devname, struct thread *td) printf("set_dumper: device name truncated from '%s' -> '%s'\n", devname, dumpdevname); } + dumper.blockbuf = malloc(di->blocksize, M_DUMPER, M_WAITOK | M_ZERO); return (0); } @@ -880,6 +885,31 @@ dump_write(struct dumperinfo *di, void *virtual, vm_offset_t physical, return (di->dumper(di->priv, virtual, physical, offset, length)); } +/* Call dumper with bounds checking. */ +int +dump_write_pad(struct dumperinfo *di, void *virtual, vm_offset_t physical, + off_t offset, size_t length, size_t *size) +{ + char *temp; + int ret; + + if (length > di->blocksize) + return (ENOMEM); + + *size = di->blocksize; + if (length == di->blocksize) + temp = virtual; + else { + temp = di->blockbuf; + memset(temp + length, 0, di->blocksize - length); + memcpy(temp, virtual, length); + } + ret = dump_write(di, temp, physical, offset, *size); + + return (ret); +} + + void mkdumpheader(struct kerneldumpheader *kdh, char *magic, uint32_t archver, uint64_t dumplen, uint32_t blksz) diff --git a/sys/sys/conf.h b/sys/sys/conf.h index 6d2cac90387c..b7d9756c3b5c 100644 --- a/sys/sys/conf.h +++ b/sys/sys/conf.h @@ -328,15 +328,18 @@ EVENTHANDLER_DECLARE(dev_clone, dev_clone_fn); struct dumperinfo { dumper_t *dumper; /* Dumping function. */ - void *priv; /* Private parts. */ - u_int blocksize; /* Size of block in bytes. */ + void *priv; /* Private parts. */ + u_int blocksize; /* Size of block in bytes. */ u_int maxiosize; /* Max size allowed for an individual I/O */ - off_t mediaoffset; /* Initial offset in bytes. */ - off_t mediasize; /* Space available in bytes. */ + off_t mediaoffset; /* Initial offset in bytes. */ + off_t mediasize; /* Space available in bytes. */ + void *blockbuf; /* Buffer for padding shorter dump blocks */ }; int set_dumper(struct dumperinfo *, const char *_devname, struct thread *td); int dump_write(struct dumperinfo *, void *, vm_offset_t, off_t, size_t); +int dump_write_pad(struct dumperinfo *, void *, vm_offset_t, off_t, size_t, + size_t *); int doadump(boolean_t); extern int dumping; /* system is dumping */ From 0a1addd293ed712585783441427a44ce2e0ae568 Mon Sep 17 00:00:00 2001 From: Phil Shafer Date: Fri, 15 Apr 2016 18:03:30 +0000 Subject: [PATCH 134/143] Import libxo 0.6.0 --- Makefile.am | 1 + configure.ac | 31 +- doc/libxo-manual.html | 1078 ++++++++++++++++------------- doc/libxo.txt | 336 ++++++--- encoder/cbor/enc_cbor.c | 2 +- libxo-config.in | 16 +- libxo/libxo.c | 563 +++++++++++++-- libxo/xo.h | 70 ++ libxo/xo_emit_f.3 | 111 +++ libxo/xo_format.5 | 318 +++++---- libxo/xo_parse_args.3 | 4 + packaging/libxo.pc.in | 6 +- packaging/libxo.rb.base.in | 8 +- tests/core/Makefile.am | 4 +- tests/core/saved/test_01.E.out | 8 + tests/core/saved/test_01.H.out | 3 +- tests/core/saved/test_01.HIPx.out | 22 + tests/core/saved/test_01.HP.out | 22 + tests/core/saved/test_01.J.out | 2 +- tests/core/saved/test_01.JP.out | 8 + tests/core/saved/test_01.T.out | 4 + tests/core/saved/test_01.X.out | 2 +- tests/core/saved/test_01.XP.out | 8 + tests/core/saved/test_12.E.err | 0 tests/core/saved/test_12.E.out | 89 +++ tests/core/saved/test_12.H.err | 0 tests/core/saved/test_12.H.out | 1 + tests/core/saved/test_12.HIPx.err | 0 tests/core/saved/test_12.HIPx.out | 160 +++++ tests/core/saved/test_12.HP.err | 0 tests/core/saved/test_12.HP.out | 160 +++++ tests/core/saved/test_12.J.err | 0 tests/core/saved/test_12.J.out | 2 + tests/core/saved/test_12.JP.err | 0 tests/core/saved/test_12.JP.out | 88 +++ tests/core/saved/test_12.T.err | 0 tests/core/saved/test_12.T.out | 20 + tests/core/saved/test_12.X.err | 0 tests/core/saved/test_12.X.out | 1 + tests/core/saved/test_12.XP.err | 0 tests/core/saved/test_12.XP.out | 84 +++ tests/core/test_01.c | 12 + tests/core/test_02.c | 1 + tests/core/test_12.c | 76 ++ tests/gettext/gt_01.c | 2 +- 45 files changed, 2498 insertions(+), 825 deletions(-) create mode 100644 libxo/xo_emit_f.3 create mode 100644 tests/core/saved/test_12.E.err create mode 100644 tests/core/saved/test_12.E.out create mode 100644 tests/core/saved/test_12.H.err create mode 100644 tests/core/saved/test_12.H.out create mode 100644 tests/core/saved/test_12.HIPx.err create mode 100644 tests/core/saved/test_12.HIPx.out create mode 100644 tests/core/saved/test_12.HP.err create mode 100644 tests/core/saved/test_12.HP.out create mode 100644 tests/core/saved/test_12.J.err create mode 100644 tests/core/saved/test_12.J.out create mode 100644 tests/core/saved/test_12.JP.err create mode 100644 tests/core/saved/test_12.JP.out create mode 100644 tests/core/saved/test_12.T.err create mode 100644 tests/core/saved/test_12.T.out create mode 100644 tests/core/saved/test_12.X.err create mode 100644 tests/core/saved/test_12.X.out create mode 100644 tests/core/saved/test_12.XP.err create mode 100644 tests/core/saved/test_12.XP.out create mode 100644 tests/core/test_12.c diff --git a/Makefile.am b/Makefile.am index e050bc46f339..cb71d522bb51 100644 --- a/Makefile.am +++ b/Makefile.am @@ -77,6 +77,7 @@ GH_PAGES_PACKAGE_DIR = ${GH_PAGES_DIR}/${GH_PACKAGING_DIR} packages: @-[ -d ${GH_PAGES_DIR} ] && set -x \ && echo "Updating packages on gh-pages ..." \ + && mkdir -p ${GH_PAGES_DIR}/${GH_PACKAGING_DIR} \ && SHA1="`openssl sha1 ${PACKAGE_FILE} | awk '{print $$2}'`" \ && SHA256="`openssl sha256 ${PACKAGE_FILE} | awk '{print $$2}'`" \ && SIZE="`ls -l ${PACKAGE_FILE} | awk '{print $$5}'`" \ diff --git a/configure.ac b/configure.ac index 1d86f0e5030c..cc371100e9bf 100644 --- a/configure.ac +++ b/configure.ac @@ -12,7 +12,7 @@ # AC_PREREQ(2.2) -AC_INIT([libxo], [0.4.7], [phil@juniper.net]) +AC_INIT([libxo], [0.5.0], [phil@juniper.net]) AM_INIT_AUTOMAKE([-Wall -Werror foreign -Wno-portability]) # Support silent build rules. Requires at least automake-1.11. @@ -74,6 +74,7 @@ AC_CHECK_HEADERS([ctype.h errno.h stdio.h stdlib.h]) AC_CHECK_HEADERS([string.h sys/param.h unistd.h ]) AC_CHECK_HEADERS([sys/sysctl.h]) AC_CHECK_HEADERS([threads.h]) +AC_CHECK_HEADERS([monitor.h]) dnl humanize_number(3) is a great function, but it's not standard. dnl Note Macosx has the function in libutil.a but doesn't ship the @@ -148,10 +149,18 @@ fi AC_SUBST(GETTEXT_CFLAGS) AC_SUBST(GETTEXT_LIBS) -GETTEXT_BINDIR=${GETTEXT_PREFIX}/bin -AC_SUBST(GETTEXT_BINDIR) GETTEXT_LIBDIR=${GETTEXT_PREFIX}/lib AC_SUBST(GETTEXT_LIBDIR) +if test -x ${GETTEXT_PREFIX}/bin/msgfmt ; then + GETTEXT_BINDIR=${GETTEXT_PREFIX}/bin +elif test -x ${GETTEXT_PREFIX}/local/bin/msgfmt ; then + GETTEXT_BINDIR=${GETTEXT_PREFIX}/local/bin +else + AC_MSG_NOTICE("could not find msgfmt tool") + # Use a (bad) fall back value + GETTEXT_BINDIR=${GETTEXT_PREFIX}/bin +fi +AC_SUBST(GETTEXT_BINDIR) AM_CONDITIONAL([HAVE_GETTEXT], [test "$HAVE_GETTEXT" = "yes"]) @@ -287,6 +296,18 @@ if test "${LIBXO_WCWIDTH}" != "no"; then AC_DEFINE([LIBXO_WCWIDTH], [1], [Enable local wcwidth implementation]) fi +AC_MSG_CHECKING([retain hash bucket size]) +AC_ARG_WITH(retain-size, + [ --with-retain-size=[DIR] Specify retain hash bucket size (in bits)], + [XO_RETAIN_SIZE=$withval], + [XO_RETAIN_SIZE=default] +) + +AC_MSG_RESULT([$XO_RETAIN_SIZE]) +if test "${XO_RETAIN_SIZE}" != "default"; then + AC_DEFINE_UNQUOTED([XO_RETAIN_SIZE], ${XO_RETAIN_SIZE}, [Retain hash bucket size]) +fi + AC_CHECK_LIB([m], [lrint]) AM_CONDITIONAL([HAVE_LIBM], [test "$HAVE_LIBM" != "no"]) @@ -347,12 +368,15 @@ XO_SRCDIR=${srcdir} XO_LIBDIR=${libdir} XO_BINDIR=${bindir} XO_INCLUDEDIR=${includedir} +XO_CFLAGS="${CFLAGS}" +AC_SUBST(XO_LIBS) AC_SUBST(XO_SRCDIR) AC_SUBST(XO_LIBDIR) AC_SUBST(XO_BINDIR) AC_SUBST(XO_INCLUDEDIR) AC_SUBST(XO_LIBEXT) +AC_SUBST(XO_CFLAGS) AC_ARG_WITH(encoder-dir, [ --with-encoder-dir=[DIR] Specify location of encoder libraries], @@ -449,4 +473,5 @@ AC_MSG_NOTICE([summary of build options: isthreaded: ${HAVE_ISTHREADED:-no} thread-local: ${THREAD_LOCAL:-no} local wcwidth: ${LIBXO_WCWIDTH:-no} + retain size: ${XO_RETAIN_SIZE:-no} ]) diff --git a/doc/libxo-manual.html b/doc/libxo-manual.html index 47881da91ab5..4db374b394f5 100644 --- a/doc/libxo-manual.html +++ b/doc/libxo-manual.html @@ -515,7 +515,7 @@ li.indline1 { } @top-right { - content: "December 2015"; + content: "April 2016"; } @top-center { @@ -22009,7 +22009,7 @@ jQuery(function ($) { -December 30, 2015 +April 15, 2016

libxo: The Easy Way to Generate text, XML, JSON, and HTML output
libxo-manual

@@ -22130,46 +22130,54 @@ jQuery(function ($) { Field Modifiers @@ -22208,42 +22216,38 @@ jQuery(function ($) {
  • 2.2.11   
    +Retaining Parsed Format Information +
  • +
  • +
    2.2.12   
    Example
  • 2.3   
    -Command-line Arguments -
  • -
  • -
    2.4   
    Representing Hierarchy
  • -
    2.5   
    -Handles -
  • -
  • -
    2.6   
    -UTF-8 +
    2.4   
    +Command-line Arguments
  • @@ -22252,7 +22256,7 @@ jQuery(function ($) { The libxo API
    • 3.1   
      -Handles
        +Handles

        @@ -23356,6 +23363,11 @@ jQuery(function ($) { +a +argument +The content appears as a 'const char *' argument + + c colon A colon (":") is appended after the label @@ -23435,87 +23447,107 @@ jQuery(function ($) {

        Roles and modifiers can also use more verbose names, when preceeded by a comma. For example, the modifier string "Lwc" (or "L,white,colon") means the field has a label role (text that describes the next field) and should be followed by a colon ('c') and a space ('w'). The modifier string "Vkq" (or ":key,quote") means the field has a value role (the default role), that it is a key for the current instance, and that the value should be quoted when encoded for JSON.

        Section Contents:

        -The Colon Modifier ({c:}) +The Argument Modifier ({a:})

        -

        The colon modifier appends a single colon to the data value:

        +

        The argument modifier indicates that the content of the field descriptor will be placed as a UTF-8 string (const char *) argument within the xo_emit parameters.

             EXAMPLE:
        -      xo_emit("{Lc:Name}{:name}\n", "phil");
        +      xo_emit("{La:} {a:}\n", "Label text", "label", "value");
             TEXT:
        -      Name:phil
        -	    

        The colon modifier is only used for the TEXT and HTML output styles. It is commonly combined with the space modifier ('{w:}'). It is purely a convenience feature.

        + Label text value + JSON: + "label": "value" + XML: + <label>value</label> +

        The argument modifier allows field names for value fields to be passed on the stack, avoiding the need to build a field descriptor using snprintf. For many field roles, the argument modifier is not needed, since those roles have specific mechanisms for arguments, such as "{C:fg‑%s}".

        +The Colon Modifier ({c:}) +

        +

        The colon modifier appends a single colon to the data value:

        +
        +    EXAMPLE:
        +      xo_emit("{Lc:Name}{:name}\n", "phil");
        +    TEXT:
        +      Name:phil
        +	    

        The colon modifier is only used for the TEXT and HTML output styles. It is commonly combined with the space modifier ('{w:}'). It is purely a convenience feature.

        +
        +
        +

        + The Display Modifier ({d:})

        -

        The display modifier indicated the field should only be generated for the display output styles, TEXT and HTML.

        -
        +

        The display modifier indicated the field should only be generated for the display output styles, TEXT and HTML.

        +
             EXAMPLE:
               xo_emit("{Lcw:Name}{d:name} {:id/%d}\n", "phil", 1);
             TEXT:
               Name: phil 1
             XML:
               <id>1</id>
        -	    

        The display modifier is the opposite of the encoding modifier, and they are often used to give to distinct views of the underlying data.

        +

        The display modifier is the opposite of the encoding modifier, and they are often used to give to distinct views of the underlying data.

        -

        +

        +2.2.2.4 

        The Encoding Modifier ({e:})

        -

        The display modifier indicated the field should only be generated for the display output styles, TEXT and HTML.

        -
        +

        The display modifier indicated the field should only be generated for the display output styles, TEXT and HTML.

        +
             EXAMPLE:
               xo_emit("{Lcw:Name}{:name} {e:id/%d}\n", "phil", 1);
             TEXT:
               Name: phil
             XML:
               <name>phil</name><id>1</id>
        -	    

        The encoding modifier is the opposite of the display modifier, and they are often used to give to distinct views of the underlying data.

        -
        -
        -

        - -The Gettext Modifier ({g:}) -

        -

        The gettext modifier is used to translate individual fields using the gettext domain (typically set using the "{G:}" role) and current language settings. Once libxo renders the field value, it is passed to gettext(3), where it is used as a key to find the native language translation.

        -

        In the following example, the strings "State" and "full" are passed to gettext() to find locale-based translated strings.

        -
        -    xo_emit("{Lgwc:State}{g:state}\n", "full");
        -	    

        See Section 2.2.1.3, Section 2.2.2.9, and Section 9.5 for additional details.

        +

        The encoding modifier is the opposite of the display modifier, and they are often used to give to distinct views of the underlying data.

        +The Gettext Modifier ({g:}) +

        +

        The gettext modifier is used to translate individual fields using the gettext domain (typically set using the "{G:}" role) and current language settings. Once libxo renders the field value, it is passed to gettext(3), where it is used as a key to find the native language translation.

        +

        In the following example, the strings "State" and "full" are passed to gettext() to find locale-based translated strings.

        +
        +    xo_emit("{Lgwc:State}{g:state}\n", "full");
        +	    

        See Section 2.2.1.3, Section 2.2.2.10, and Section 9.5 for additional details.

        +
        +
        +

        + The Humanize Modifier ({h:})

        -

        The humanize modifier is used to render large numbers as in a human-readable format. While numbers like "44470272" are completely readable to computers and savants, humans will generally find "44M" more meaningful.

        -

        "hn" can be used as an alias for "humanize".

        -

        The humanize modifier only affects display styles (TEXT and HMTL). The "no‑humanize" option (See Section 3.4.6) will block the function of the humanize modifier.

        -

        There are a number of modifiers that affect details of humanization. These are only available in as full names, not single characters. The "hn‑space" modifier places a space between the number and any multiplier symbol, such as "M" or "K" (ex: "44 K"). The "hn‑decimal" modifier will add a decimal point and a single tenths digit when the number is less than 10 (ex: "4.4K"). The "hn‑1000" modifier will use 1000 as divisor instead of 1024, following the JEDEC-standard instead of the more natural binary powers-of-two tradition.

        -
        +

        The humanize modifier is used to render large numbers as in a human-readable format. While numbers like "44470272" are completely readable to computers and savants, humans will generally find "44M" more meaningful.

        +

        "hn" can be used as an alias for "humanize".

        +

        The humanize modifier only affects display styles (TEXT and HMTL). The "no‑humanize" option (See Section 3.4.6) will block the function of the humanize modifier.

        +

        There are a number of modifiers that affect details of humanization. These are only available in as full names, not single characters. The "hn‑space" modifier places a space between the number and any multiplier symbol, such as "M" or "K" (ex: "44 K"). The "hn‑decimal" modifier will add a decimal point and a single tenths digit when the number is less than 10 (ex: "4.4K"). The "hn‑1000" modifier will use 1000 as divisor instead of 1024, following the JEDEC-standard instead of the more natural binary powers-of-two tradition.

        +
             EXAMPLE:
                 xo_emit("{h:input/%u}, {h,hn-space:output/%u}, "
                     "{h,hn-decimal:errors/%u}, {h,hn-1000:capacity/%u}, "
        @@ -23523,19 +23555,19 @@ jQuery(function ($) {
                     input, output, errors, capacity, remaining);
             TEXT:
                 21, 57 K, 96M, 44M, 1.2G
        -	    

        In the HTML style, the original numeric value is rendered in the "data‑number" attribute on the <div> element:

        -
        +	    

        In the HTML style, the original numeric value is rendered in the "data‑number" attribute on the <div> element:

        +
             <div class="data" data-tag="errors"
                  data-number="100663296">96M</div>
         	    
        -

        +

        +2.2.2.7 

        The Key Modifier ({k:}) -

        The key modifier is used to indicate that a particular field helps uniquely identify an instance of list data.

        -
        +

        The key modifier is used to indicate that a particular field helps uniquely identify an instance of list data.

        +
             EXAMPLE:
                 xo_open_list("user");
                 for (i = 0; i < num_users; i++) {
        @@ -23545,16 +23577,16 @@ jQuery(function ($) {
                     xo_close_instance("user");
                 }
                 xo_close_list("user");
        -	    

        Currently the key modifier is only used when generating XPath value for the HTML output style when XOF_XPATH is set, but other uses are likely in the near future.

        +

        Currently the key modifier is only used when generating XPath value for the HTML output style when XOF_XPATH is set, but other uses are likely in the near future.

        -

        +

        +2.2.2.8 

        The Leaf-List Modifier ({l:}) -

        The leaf-list modifier is used to distinguish lists where each instance consists of only a single value. In XML, these are rendered as single elements, where JSON renders them as arrays.

        -
        +

        The leaf-list modifier is used to distinguish lists where each instance consists of only a single value. In XML, these are rendered as single elements, where JSON renders them as arrays.

        +
             EXAMPLE:
                 for (i = 0; i < num_users; i++) {
                     xo_emit("Member {l:user}\n", user[i].u_name);
        @@ -23564,16 +23596,16 @@ jQuery(function ($) {
                 <user>pallavi</user>
             JSON:
                 "user": [ "phil", "pallavi" ]
        -	    

        The name of the field must match the name of the leaf list.

        +

        The name of the field must match the name of the leaf list.

        -

        +

        +2.2.2.9 

        The No-Quotes Modifier ({n:}) -

        The no-quotes modifier (and its twin, the 'quotes' modifier) affect the quoting of values in the JSON output style. JSON uses quotes for string value, but no quotes for numeric, boolean, and null data. xo_emit applies a simple heuristic to determine whether quotes are needed, but often this needs to be controlled by the caller.

        -
        +

        The no-quotes modifier (and its twin, the 'quotes' modifier) affect the quoting of values in the JSON output style. JSON uses quotes for string value, but no quotes for numeric, boolean, and null data. xo_emit applies a simple heuristic to determine whether quotes are needed, but often this needs to be controlled by the caller.

        +
             EXAMPLE:
               const char *bool = is_true ? "true" : "false";
               xo_emit("{n:fancy/%s}", bool);
        @@ -23581,45 +23613,61 @@ jQuery(function ($) {
               "fancy": true
         	    
        -

        - -The Plural Modifier ({p:}) -

        -

        The plural modifier selects the appropriate plural form of an expression based on the most recent number emitted and the current language settings. The contents of the field should be the singular and plural English values, separated by a comma:

        -
        -    xo_emit("{:bytes} {Ngp:byte,bytes}\n", bytes);
        -	    

        The plural modifier is meant to work with the gettext modifier ({g:}) but can work independently. See Section 2.2.2.4.

        -

        When used without the gettext modifier or when the message does not appear in the message catalog, the first token is chosen when the last numeric value is equal to 1; otherwise the second value is used, mimicking the simple pluralization rules of English.

        -

        When used with the gettext modifier, the ngettext(3) function is called to handle the heavy lifting, using the message catalog to convert the singular and plural forms into the native language.

        -
        -

        -The Quotes Modifier ({q:}) +The Plural Modifier ({p:})

        -

        The quotes modifier (and its twin, the 'no‑quotes' modifier) affect the quoting of values in the JSON output style. JSON uses quotes for string value, but no quotes for numeric, boolean, and null data. xo_emit applies a simple heuristic to determine whether quotes are needed, but often this needs to be controlled by the caller.

        +

        The plural modifier selects the appropriate plural form of an expression based on the most recent number emitted and the current language settings. The contents of the field should be the singular and plural English values, separated by a comma:

        -    EXAMPLE:
        -      xo_emit("{q:time/%d}", 2014);
        -    JSON:
        -      "year": "2014"
        -	    
        + xo_emit("{:bytes} {Ngp:byte,bytes}\n", bytes); +

        The plural modifier is meant to work with the gettext modifier ({g:}) but can work independently. See Section 2.2.2.5.

        +

        When used without the gettext modifier or when the message does not appear in the message catalog, the first token is chosen when the last numeric value is equal to 1; otherwise the second value is used, mimicking the simple pluralization rules of English.

        +

        When used with the gettext modifier, the ngettext(3) function is called to handle the heavy lifting, using the message catalog to convert the singular and plural forms into the native language.

        +

        +The Quotes Modifier ({q:}) +

        +

        The quotes modifier (and its twin, the 'no‑quotes' modifier) affect the quoting of values in the JSON output style. JSON uses quotes for string value, but no quotes for numeric, boolean, and null data. xo_emit applies a simple heuristic to determine whether quotes are needed, but often this needs to be controlled by the caller.

        +
        +    EXAMPLE:
        +      xo_emit("{q:time/%d}", 2014);
        +    JSON:
        +      "year": "2014"
        +	    

        The heuristic is based on the format; if the format uses any of the following conversion specifiers, then no quotes are used:

        +
        +    d i o u x X D O U e E f F g G a A c C p
        +	    
        +
        +

        + +The Trim Modifier ({t:}) +

        +

        The trim modifier removes any leading or trailing whitespace from the value.

        +
        +    EXAMPLE:
        +      xo_emit("{t:description}", "   some  input   ");
        +    JSON:
        +      "description": "some input"
        +	    
        +
        +

        + The White Space Modifier ({w:})

        -

        The white space modifier appends a single space to the data value:

        -
        +

        The white space modifier appends a single space to the data value:

        +
             EXAMPLE:
               xo_emit("{Lw:Name}{:name}\n", "phil");
             TEXT:
               Name phil
        -	    

        The white space modifier is only used for the TEXT and HTML output styles. It is commonly combined with the colon modifier ('{c:}'). It is purely a convenience feature.

        -

        Note that the sense of the 'w' modifier is reversed for the units role ({Uw:}); a blank is added before the contents, rather than after it.

        +

        The white space modifier is only used for the TEXT and HTML output styles. It is commonly combined with the colon modifier ('{c:}'). It is purely a convenience feature.

        +

        Note that the sense of the 'w' modifier is reversed for the units role ({Uw:}); a blank is added before the contents, rather than after it.

        @@ -23632,7 +23680,7 @@ jQuery(function ($) {

        If the format string is not provided for a value field, it defaults to "%s".

        Note a field definition can contain zero or more printf-style 'directives', which are sequences that start with a '%' and end with one of following characters: "diouxXDOUeEfFgGaAcCsSp". Each directive is matched by one of more arguments to the xo_emit function.

        The format string has the form:

        -
        +
           '%' format-modifier * format-character
         	    

        The format- modifier can be:

        @@ -23829,8 +23877,42 @@ jQuery(function ($) { UTF-8 and Locale Strings

        For strings, the 'h' and 'l' modifiers affect the interpretation of the bytes pointed to argument. The default '%s' string is a 'char *' pointer to a string encoded as UTF-8. Since UTF-8 is compatible with ASCII data, a normal 7-bit ASCII string can be used. '%ls' expects a 'wchar_t *' pointer to a wide-character string, encoded as a 32-bit Unicode values. '%hs' expects a 'char *' pointer to a multi-byte string encoded with the current locale, as given by the LC_CTYPE, LANG, or LC_ALL environment varibles. The first of this list of variables is used and if none of the variables are set, the locale defaults to "UTF‑8".

        -

        For example, a function is passed a locale-base name, a hat size, and a time value. The hat size is formatted in a UTF-8 (ASCII) string, and the time value is formatted into a wchar_t string.

        -
        +

        libxo will convert these arguments as needed to either UTF-8 (for XML, JSON, and HTML styles) or locale-based strings for display in text style.

        +
        +   xo_emit("Alll strings are utf-8 content {:tag/%ls}",
        +           L"except for wide strings");
        +	    

        "%S" is equivalent to "%ls".

        +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        FormatArgument TypeArgument Contents
        %sconst char *UTF-8 string
        %Sconst char *UTF-8 string (alias for '%s')
        %lsconst wchar_t *Wide character UNICODE string
        %hsconst char *locale-based string
        +

        For example, a function is passed a locale-base name, a hat size, and a time value. The hat size is formatted in a UTF-8 (ASCII) string, and the time value is formatted into a wchar_t string.

        +
             void print_order (const char *name, int size,
                               struct tm *timep) {
                 char buf[32];
        @@ -23849,10 +23931,10 @@ jQuery(function ($) {
                 xo_emit("It was ordered on {:order-time/%ls}.\n",
                         when);
             }
        -	    

        It is important to note that xo_emit will perform the conversion required to make appropriate output. Text style output uses the current locale (as described above), while XML, JSON, and HTML use UTF-8.

        -

        UTF-8 and locale-encoded strings can use multiple bytes to encode one column of data. The traditional "precision'" (aka "max‑width") value for "%s" printf formatting becomes overloaded since it specifies both the number of bytes that can be safely referenced and the maximum number of columns to emit. xo_emit uses the precision as the former, and adds a third value for specifying the maximum number of columns.

        -

        In this example, the name field is printed with a minimum of 3 columns and a maximum of 6. Up to ten bytes of data at the location given by 'name' are in used in filling those columns.

        -
        +	    

        It is important to note that xo_emit will perform the conversion required to make appropriate output. Text style output uses the current locale (as described above), while XML, JSON, and HTML use UTF-8.

        +

        UTF-8 and locale-encoded strings can use multiple bytes to encode one column of data. The traditional "precision'" (aka "max‑width") value for "%s" printf formatting becomes overloaded since it specifies both the number of bytes that can be safely referenced and the maximum number of columns to emit. xo_emit uses the precision as the former, and adds a third value for specifying the maximum number of columns.

        +

        In this example, the name field is printed with a minimum of 3 columns and a maximum of 6. Up to ten bytes of data at the location given by 'name' are in used in filling those columns.

        +
             xo_emit("{:name/%3.10.6s}", name);
         	    
        @@ -23862,7 +23944,7 @@ jQuery(function ($) { Characters Outside of Field Definitions

        Characters in the format string that are not part of a field definition are copied to the output for the TEXT style, and are ignored for the JSON and XML styles. For HTML, these characters are placed in a <div> with class "text".

        -
        +
           EXAMPLE:
               xo_emit("The hat is {:size/%s}.\n", size_val);
           TEXT:
        @@ -23883,7 +23965,7 @@ jQuery(function ($) {
         "%m" Is Supported
         
         

        libxo supports the '%m' directive, which formats the error message associated with the current value of "errno". It is the equivalent of "%s" with the argument strerror(errno).

        -
        +
             xo_emit("{:filename} cannot be opened: {:error/%m}", filename);
             xo_emit("{:filename} cannot be opened: {:error/%s}",
                     filename, strerror(errno));
        @@ -23930,7 +24012,7 @@ jQuery(function ($) {
         
      • distinct encoding formats, where "{:tag/#%s/%s}" means the display styles (text and HTML) will use "#%s" where other styles use "%s";

      If none of these features are in use by your code, then using the "_p" variants might be wise.

      -
      +
      @@ -23987,14 +24069,71 @@ jQuery(function ($) {

      +Retaining Parsed Format Information +

      +

      libxo can retain the parsed internal information related to the given format string, allowing subsequent xo_emit calls, the retained information is used, avoiding repetitive parsing of the format string.

      +
      +    SYNTAX:
      +      int xo_emit_f(xo_emit_flags_t flags, const char fmt, ...);
      +    EXAMPLE:
      +      xo_emit_f(XOEF_RETAIN, "{:some/%02d}{:thing/%-6s}{:fancy}\n",
      +                     some, thing, fancy);
      +	    

      To retain parsed format information, use the XOEF_RETAIN flag to the xo_emit_f() function. A complete set of xo_emit_f functions exist to match all the xo_emit function signatures (with handles, varadic argument, and printf-like flags):

      +
      Function printf-like Equivalent
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      FunctionFlags Equivalent
      xo_emit_hvxo_emit_hvf
      xo_emit_hxo_emit_hf
      xo_emitxo_emit_f
      xo_emit_hvpxo_emit_hvfp
      xo_emit_hpxo_emit_hfp
      xo_emit_pxo_emit_fp
      +

      The format string must be immutable across multiple calls to xo_emit_f(), since the library retains the string. Typically this is done by using static constant strings, such as string literals. If the string is not immutable, the XOEF_RETAIN flag must not be used.

      +

      The functions xo_retain_clear() and xo_retain_clear_all() release internal information on either a single format string or all format strings, respectively. Neither is required, but the library will retain this information until it is cleared or the process exits.

      +
      +    const char *fmt = "{:name}  {:count/%d}\n";
      +    for (i = 0; i < 1000; i++) {
      +        xo_open_instance("item");
      +        xo_emit_f(XOEF_RETAIN, fmt, name[i], count[i]);
      +    }
      +    xo_retain_clear(fmt);
      +	    

      The retained information is kept as thread-specific data.

      + +
      +

      +
      +2.2.12 
      Example

      -

      In this example, the value for the number of items in stock is emitted:

      -
      +

      In this example, the value for the number of items in stock is emitted:

      +
               xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\n",
                       instock);
      -	    

      This call will generate the following output:

      -
      +	    

      This call will generate the following output:

      +
         TEXT: 
              In stock: 144
         XML:
      @@ -24009,8 +24148,8 @@ jQuery(function ($) {
               <div class="padding"> </div>
               <div class="data" data-tag="in-stock">144</div>
             </div>
      -	    

      Clearly HTML wins the verbosity award, and this output does not include XOF_XPATH or XOF_INFO data, which would expand the penultimate line to:

      -
      +	    

      Clearly HTML wins the verbosity award, and this output does not include XOF_XPATH or XOF_INFO data, which would expand the penultimate line to:

      +
              <div class="data" data-tag="in-stock"
                 data-xpath="/top/data/item/in-stock"
                 data-type="number"
      @@ -24021,17 +24160,148 @@ jQuery(function ($) {
       

      2.3 
      +Representing Hierarchy +

      +

      For XML and JSON, individual fields appear inside hierarchies which provide context and meaning to the fields. Unfortunately, these encoding have a basic disconnect between how lists is similar objects are represented.

      +

      XML encodes lists as set of sequential elements:

      +
      +    <user>phil</user>
      +    <user>pallavi</user>
      +    <user>sjg</user>
      +	    

      JSON encodes lists using a single name and square brackets:

      +
      +    "user": [ "phil", "pallavi", "sjg" ]
      +	    

      This means libxo needs three distinct indications of hierarchy: one for containers of hierarchy appear only once for any specific parent, one for lists, and one for each item in a list.

      +

      Section Contents:

      + +
      +

      +
      +2.3.1 
      +Containers +

      +

      A "container" is an element of a hierarchy that appears only once under any specific parent. The container has no value, but serves to contain other nodes.

      +

      To open a container, call xo_open_container() or xo_open_container_h(). The former uses the default handle and the latter accepts a specific handle.

      +
      +    int xo_open_container_h (xo_handle_t *xop, const char *name);
      +    int xo_open_container (const char *name);
      +	    

      To close a level, use the xo_close_container() or xo_close_container_h() functions:

      +
      +    int xo_close_container_h (xo_handle_t *xop, const char *name);
      +    int xo_close_container (const char *name);
      +	    

      Each open call must have a matching close call. If the XOF_WARN flag is set and the name given does not match the name of the currently open container, a warning will be generated.

      +
      +    Example:
      +
      +        xo_open_container("top");
      +        xo_open_container("system");
      +        xo_emit("{:host-name/%s%s%s", hostname,
      +                domainname ? "." : "", domainname ?: "");
      +        xo_close_container("system");
      +        xo_close_container("top");
      +
      +    Sample Output:
      +      Text:
      +        my-host.example.org
      +      XML:
      +        <top>
      +          <system>
      +              <host-name>my-host.example.org</host-name>
      +          </system>
      +        </top>
      +      JSON:
      +        "top" : {
      +          "system" : {
      +              "host-name": "my-host.example.org"
      +          }
      +        }
      +      HTML:
      +        <div class="data"
      +             data-tag="host-name">my-host.example.org</div>
      +	    
      +
      +

      +
      +2.3.2 
      +Lists and Instances +

      +

      A list is set of one or more instances that appear under the same parent. The instances contain details about a specific object. One can think of instances as objects or records. A call is needed to open and close the list, while a distinct call is needed to open and close each instance of the list:

      +
      +    xo_open_list("item");
      +
      +    for (ip = list; ip->i_title; ip++) {
      +        xo_open_instance("item");
      +        xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title);
      +        xo_close_instance("item");
      +    }
      +
      +    xo_close_list("item");
      +	    

      Getting the list and instance calls correct is critical to the proper generation of XML and JSON data.

      +
      +
      +

      +
      +2.3.3 
      +DTRT Mode +

      +

      Some users may find tracking the names of open containers, lists, and instances inconvenient. libxo offers a "Do The Right Thing" mode, where libxo will track the names of open containers, lists, and instances so the close function can be called without a name. To enable DTRT mode, turn on the XOF_DTRT flag prior to making any other libxo output.

      +
      +    xo_set_flags(NULL, XOF_DTRT);
      +	    

      Each open and close function has a version with the suffix "_d", which will close the open container, list, or instance:

      +
      +    xo_open_container("top");
      +    ...
      +    xo_close_container_d();
      +	    

      This also works for lists and instances:

      +
      +    xo_open_list("item");
      +    for (...) {
      +        xo_open_instance("item");
      +        xo_emit(...);
      +        xo_close_instance_d();
      +    }
      +    xo_close_list_d();
      +	    

      Note that the XOF_WARN flag will also cause libxo to track open containers, lists, and instances. A warning is generated when the name given to the close function and the name recorded do not match.

      +
      +
      +

      +
      +2.3.4 
      +Markers +

      +

      Markers are used to protect and restore the state of open constructs. While a marker is open, no other open constructs can be closed. When a marker is closed, all constructs open since the marker was opened will be closed.

      +

      Markers use names which are not user-visible, allowing the caller to choose appropriate internal names.

      +

      In this example, the code whiffles through a list of fish, calling a function to emit details about each fish. The marker "fish‑guts" is used to ensure that any constructs opened by the function are closed properly.

      +
      +    for (i = 0; fish[i]; i++) {
      +        xo_open_instance("fish");
      +        xo_open_marker("fish-guts");
      +        dump_fish_details(i);
      +        xo_close_marker("fish-guts");
      +    }
      +	    
      +
      +
      +

      +
      +2.4 
      Command-line Arguments

      -

      libxo uses command line options to trigger rendering behavior. The following options are recognised:

      -

      +

      libxo uses command line options to trigger rendering behavior. The following options are recognised:

      +

      • --libxo <options>
      • --libxo=<options>
      • --libxo:<brief‑options>
      -

      Options is a comma-separated list of tokens that correspond to output styles, flags, or features:

      -
      +

      Programs using libxo are expecting to call the xo_parse_args function to parse these arguments. See Section 3.4.1 for details.

      +

      Options is a comma-separated list of tokens that correspond to output styles, flags, or features:

      +
      @@ -24082,6 +24352,10 @@ jQuery(function ($) { + + + + @@ -24094,6 +24368,10 @@ jQuery(function ($) { + + + + @@ -24123,165 +24401,7 @@ jQuery(function ($) {
      Token ActionDo not initialize the locale setting
      no-retainPrevent retaining formatting information
      no-top Do not emit a top set of braces (JSON)
      Emit pretty-printed output
      retainForce retaining formatting information
      text Emit TEXT output
      -

      The brief options are detailed in Section 3.4.6.

      -
      -
      -

      -
      -2.4 
      -Representing Hierarchy -

      -

      For XML and JSON, individual fields appear inside hierarchies which provide context and meaning to the fields. Unfortunately, these encoding have a basic disconnect between how lists is similar objects are represented.

      -

      XML encodes lists as set of sequential elements:

      -
      -    <user>phil</user>
      -    <user>pallavi</user>
      -    <user>sjg</user>
      -	    

      JSON encodes lists using a single name and square brackets:

      -
      -    "user": [ "phil", "pallavi", "sjg" ]
      -	    

      This means libxo needs three distinct indications of hierarchy: one for containers of hierarchy appear only once for any specific parent, one for lists, and one for each item in a list.

      -

      Section Contents:

      - -
      -

      -
      -2.4.1 
      -Containers -

      -

      A "container" is an element of a hierarchy that appears only once under any specific parent. The container has no value, but serves to contain other nodes.

      -

      To open a container, call xo_open_container() or xo_open_container_h(). The former uses the default handle and the latter accepts a specific handle.

      -
      -    int xo_open_container_h (xo_handle_t *xop, const char *name);
      -    int xo_open_container (const char *name);
      -	    

      To close a level, use the xo_close_container() or xo_close_container_h() functions:

      -
      -    int xo_close_container_h (xo_handle_t *xop, const char *name);
      -    int xo_close_container (const char *name);
      -	    

      Each open call must have a matching close call. If the XOF_WARN flag is set and the name given does not match the name of the currently open container, a warning will be generated.

      -
      -    Example:
      -
      -        xo_open_container("top");
      -        xo_open_container("system");
      -        xo_emit("{:host-name/%s%s%s", hostname,
      -                domainname ? "." : "", domainname ?: "");
      -        xo_close_container("system");
      -        xo_close_container("top");
      -
      -    Sample Output:
      -      Text:
      -        my-host.example.org
      -      XML:
      -        <top>
      -          <system>
      -              <host-name>my-host.example.org</host-name>
      -          </system>
      -        </top>
      -      JSON:
      -        "top" : {
      -          "system" : {
      -              "host-name": "my-host.example.org"
      -          }
      -        }
      -      HTML:
      -        <div class="data"
      -             data-tag="host-name">my-host.example.org</div>
      -	    
      -
      -

      -
      -2.4.2 
      -Lists and Instances -

      -

      A list is set of one or more instances that appear under the same parent. The instances contain details about a specific object. One can think of instances as objects or records. A call is needed to open and close the list, while a distinct call is needed to open and close each instance of the list:

      -
      -    xo_open_list("item");
      -
      -    for (ip = list; ip->i_title; ip++) {
      -        xo_open_instance("item");
      -        xo_emit("{L:Item} '{:name/%s}':\n", ip->i_title);
      -        xo_close_instance("item");
      -    }
      -
      -    xo_close_list("item");
      -	    

      Getting the list and instance calls correct is critical to the proper generation of XML and JSON data.

      -
      -
      -

      -
      -2.4.3 
      -DTRT Mode -

      -

      Some users may find tracking the names of open containers, lists, and instances inconvenient. libxo offers a "Do The Right Thing" mode, where libxo will track the names of open containers, lists, and instances so the close function can be called without a name. To enable DTRT mode, turn on the XOF_DTRT flag prior to making any other libxo output.

      -
      -    xo_set_flags(NULL, XOF_DTRT);
      -	    

      Each open and close function has a version with the suffix "_d", which will close the open container, list, or instance:

      -
      -    xo_open_container("top");
      -    ...
      -    xo_close_container_d();
      -	    

      This also works for lists and instances:

      -
      -    xo_open_list("item");
      -    for (...) {
      -        xo_open_instance("item");
      -        xo_emit(...);
      -        xo_close_instance_d();
      -    }
      -    xo_close_list_d();
      -	    

      Note that the XOF_WARN flag will also cause libxo to track open containers, lists, and instances. A warning is generated when the name given to the close function and the name recorded do not match.

      -
      -
      -

      -
      -2.4.4 
      -Markers -

      -

      Markers are used to protect and restore the state of open constructs. While a marker is open, no other open constructs can be closed. When a marker is closed, all constructs open since the marker was opened will be closed.

      -

      Markers use names which are not user-visible, allowing the caller to choose appropriate internal names.

      -

      In this example, the code whiffles through a list of fish, calling a function to emit details about each fish. The marker "fish‑guts" is used to ensure that any constructs opened by the function are closed properly.

      -
      -    for (i = 0; fish[i]; i++) {
      -        xo_open_instance("fish");
      -        xo_open_marker("fish-guts");
      -        dump_fish_details(i);
      -        xo_close_marker("fish-guts");
      -    }
      -	    
      -
      -
      -

      -
      -2.5 
      -Handles -

      -

      libxo uses "handles" to control its rendering functionality. The handle contains state and buffered data, as well as callback functions to process data.

      -

      A default handle is used when a NULL is passed to functions accepting a handle. This handle is initialized to write its data to stdout using the default style of text (XO_STYLE_TEXT).

      -

      For the convenience of callers, the libxo library includes handle-less functions that implicitly use the default handle. Any function that takes a handle will use the default handle is a value of NULL is passed in place of a valid handle.

      -

      For example, the following are equivalent:

      -
      -    xo_emit("test");
      -    xo_emit_h(NULL, "test");
      -	    

      Handles are created using xo_create() and destroy using xo_destroy().

      -
      -
      -

      -
      -2.6 
      -UTF-8 -

      -

      All strings for libxo must be UTF-8. libxo will handle turning them into locale-based strings for display to the user.

      -

      The only exception is argument formatted using the "%ls" format, which require a wide character string (wchar_t *) as input. libxo will convert these arguments as needed to either UTF-8 (for XML, JSON, and HTML styles) or locale-based strings for display in text style.

      -
      -   xo_emit("Alll strings are utf-8 content {:tag/%ls}",
      -           L"except for wide strings");
      -	    

      "%S" is equivalent to "%ls".

      +

      The brief options are detailed in Section 3.4.6.


      @@ -24294,7 +24414,7 @@ jQuery(function ($) {

      This section gives details about the functions in libxo, how to call them, and the actions they perform.

      Section Contents:

        -
      • Section 3.1
      • +
      • Section 3.1
      • Section 3.2
      • Section 3.3
      • Section 3.4
      • @@ -24305,13 +24425,19 @@ jQuery(function ($) {

        3.1 
        -Handles +Handles

        -

        Handles give an abstraction for libxo that encapsulates the state of a stream of output. Handles have the data type "xo_handle_t" and are opaque to the caller.

        -

        The library has a default handle that is automatically initialized. By default, this handle will send text style output to standard output. The xo_set_style and xo_set_flags functions can be used to change this behavior.

        -

        Many libxo functions take a handle as their first parameter; most that do not use the default handle. Any function taking a handle can be passed NULL to access the default handle.

        +

        libxo uses "handles" to control its rendering functionality. The handle contains state and buffered data, as well as callback functions to process data.

        +

        Handles give an abstraction for libxo that encapsulates the state of a stream of output. Handles have the data type "xo_handle_t" and are opaque to the caller.

        +

        The library has a default handle that is automatically initialized. By default, this handle will send text style output (XO_STYLE_TEXT) to standard output. The xo_set_style and xo_set_flags functions can be used to change this behavior.

        For the typical command that is generating output on standard output, there is no need to create an explicit handle, but they are available when needed, e.g., for daemons that generate multiple streams of output.

        -

        Section Contents:

        +

        Many libxo functions take a handle as their first parameter; most that do not use the default handle. Any function taking a handle can be passed NULL to access the default handle. For the convenience of callers, the libxo library includes handle-less functions that implicitly use the default handle.

        +

        For example, the following are equivalent:

        +
        +    xo_emit("test");
        +    xo_emit_h(NULL, "test");
        +	    

        Handles are created using xo_create() and destroy using xo_destroy().

        +

        Section Contents:

        • Section 3.1.1
        • Section 3.1.2
        • @@ -24327,7 +24453,7 @@ jQuery(function ($) { xo_create

          A handle can be allocated using the xo_create() function:

          -
          +
               xo_handle_t *xo_create (unsigned style, unsigned flags);
           
             Example:
          @@ -24343,7 +24469,7 @@ jQuery(function ($) {
           xo_create_to_file
           
           

          By default, libxo writes output to standard output. A convenience function is provided for situations when output should be written to a different file:

          -
          +
               xo_handle_t *xo_create_to_file (FILE *fp, unsigned style,
                                               unsigned flags);
           	    

          Use the XOF_CLOSE_FP flag to trigger a call to fclose() for the FILE pointer when the handle is destroyed.

          @@ -24355,7 +24481,7 @@ jQuery(function ($) { xo_set_writer

          The xo_set_writer function allows custom 'write' functions which can tailor how libxo writes data. An opaque argument is recorded and passed back to the write function, allowing the function to acquire context information. The 'close' function can release this opaque data and any other resources as needed. The flush function can flush buffered data associated with the opaque object.

          -
          +
               void xo_set_writer (xo_handle_t *xop, void *opaque,
                                   xo_write_func_t write_func,
                                   xo_close_func_t close_func);
          @@ -24368,10 +24494,10 @@ jQuery(function ($) {
           xo_set_style
           
           

          To set the style, use the xo_set_style() function:

          -
          +
               void xo_set_style(xo_handle_t *xop, unsigned style);
           	    

          To use the default handle, pass a NULL handle:

          -
          +
               xo_set_style(NULL, XO_STYLE_XML);
           	    

          Section Contents:

            @@ -24385,7 +24511,7 @@ jQuery(function ($) { Output Styles (XO_STYLE_*)

            The libxo functions accept a set of output styles:

            -
            +
            @@ -24417,10 +24543,10 @@ jQuery(function ($) { xo_set_style_name

            The xo_set_style_name() can be used to set the style based on a name encoded as a string:

            -
            +
                 int xo_set_style_name (xo_handle_t *xop, const char *style);
             	    

            The name can be any of the styles: "text", "xml", "json", or "html".

            -
            +
                 EXAMPLE:
                     xo_set_style_name(NULL, "html");
             	    
            @@ -24432,10 +24558,10 @@ jQuery(function ($) { xo_set_flags

            To set the flags, use the xo_set_flags() function:

            -
            +
                 void xo_set_flags(xo_handle_t *xop, unsigned flags);
             	    

            To use the default handle, pass a NULL handle:

            -
            +
                 xo_set_style(NULL, XO_STYLE_XML);
             	    

            Section Contents:

              @@ -24450,7 +24576,7 @@ jQuery(function ($) { Flags (XOF_*)

              The set of valid flags include:

              -
            Flag Description
            +
            @@ -24528,7 +24654,7 @@ jQuery(function ($) {

            The XOF_WARN flag requests that warnings will trigger diagnostic output (on standard error) when the library notices errors during operations, or with arguments to functions. Without warnings enabled, such conditions are ignored.

            Warnings allow developers to debug their interaction with libxo. The function "xo_failure" can used as a breakpoint for a debugger, regardless of whether warnings are enabled.

            If the style is XO_STYLE_HTML, the following additional flags can be used:

            -
            Flag Description
            +
            @@ -24547,7 +24673,7 @@ jQuery(function ($) {

            The XOF_XPATH flag enables the emission of XPath expressions detailing the hierarchy of XML elements used to encode the data field, if the XPATH style of output were requested.

            The XOF_INFO flag encodes additional informational fields for HTML output. See Section 3.4.4 for details.

            If the style is XO_STYLE_XML, the following additional flags can be used:

            -
            Flag Description
            +
            @@ -24558,7 +24684,7 @@ jQuery(function ($) {
            Flag Description

            The XOF_KEYS flag adds 'key' attribute to the XML encoding for field definitions that use the 'k' modifier. The key attribute has the value "key":

            -
            +
                 xo_emit("{k:name}", item);
             
               XML:
            @@ -24571,7 +24697,7 @@ jQuery(function ($) {
             xo_clear_flags
             
             

            The xo_clear_flags() function turns off the given flags in a specific handle.

            -
            +
                 void xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags);
             	    
            @@ -24581,9 +24707,9 @@ jQuery(function ($) { xo_set_options

            The xo_set_options() function accepts a comma-separated list of styles and flags and enables them for a specific handle.

            -
            +
                 int xo_set_options (xo_handle_t *xop, const char *input);
            -	    

            The options are identical to those listed in Section 2.3.

            +

            The options are identical to those listed in Section 2.4.

            @@ -24593,7 +24719,7 @@ jQuery(function ($) { xo_destroy

            The xo_destroy function releases a handle and any resources it is using. Calling xo_destroy with a NULL handle will release any resources associated with the default handle.

            -
            +
                 void xo_destroy(xo_handle_t *xop);
             	    
            @@ -24604,33 +24730,57 @@ jQuery(function ($) { Emitting Content (xo_emit)

            The following functions are used to emit output:

            -
            +
                 int xo_emit (const char *fmt, ...);
                 int xo_emit_h (xo_handle_t *xop, const char *fmt, ...);
                 int xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap);
            -	    

            The "fmt" argument is a string containing field descriptors as specified in Section 2.2. The use of a handle is optional and NULL can be passed to access the internal 'default' handle. See Section 2.5.

            +

            The "fmt" argument is a string containing field descriptors as specified in Section 2.2. The use of a handle is optional and NULL can be passed to access the internal 'default' handle. See Section 3.1.

            The remaining arguments to xo_emit() and xo_emit_h() are a set of arguments corresponding to the fields in the format string. Care must be taken to ensure the argument types match the fields in the format string, since an inappropriate cast can ruin your day. The vap argument to xo_emit_hv() points to a variable argument list that can be used to retrieve arguments via va_arg().

            Section Contents:

            +Single Field Emitting Functions (xo_emit_field) +

            +

            The following functions can also make output, but only make a single field at a time:

            +
            +    int xo_emit_field_hv (xo_handle_t *xop, const char *rolmod,
            +                  const char *contents, const char *fmt, 
            +                  const char *efmt, va_list vap);
            +
            +    int xo_emit_field_h (xo_handle_t *xop, const char *rolmod, 
            +                 const char *contents, const char *fmt,
            +                 const char *efmt, ...);
            +
            +    int xo_emit_field (const char *rolmod, const char *contents,
            +                 const char *fmt, const char *efmt, ...);
            +	    

            These functions are intended to avoid the scenario where one would otherwise need to compose a format descriptors using snprintf(). The individual parts of the format descriptor are passed in distinctly.

            +
            +    xo_emit("T", "Host name is ", NULL, NULL);
            +    xo_emit("V", "host-name", NULL, NULL, host-name);
            +	    
            +
            +

            +
            +3.2.2 
            Attributes (xo_attr)

            -

            The xo_attr() function emits attributes for the XML output style.

            -
            +

            The xo_attr() function emits attributes for the XML output style.

            +
                 int xo_attr (const char *name, const char *fmt, ...);
                 int xo_attr_h (xo_handle_t *xop, const char *name, 
                                const char *fmt, ...);
                 int xo_attr_hv (xo_handle_t *xop, const char *name, 
                                const char *fmt, va_list vap);
            -	    

            The name parameter give the name of the attribute to be encoded. The fmt parameter gives a printf-style format string used to format the value of the attribute using any remaining arguments, or the vap parameter passed to xo_attr_hv().

            -
            +	    

            The name parameter give the name of the attribute to be encoded. The fmt parameter gives a printf-style format string used to format the value of the attribute using any remaining arguments, or the vap parameter passed to xo_attr_hv().

            +
                 EXAMPLE:
                   xo_attr("seconds", "%ld", (unsigned long) login_time);
                   struct tm *tmp = localtime(login_time);
            @@ -24638,34 +24788,34 @@ jQuery(function ($) {
                   xo_emit("Logged in at {:login-time}\n", buf);
                 XML:
                     <login-time seconds="1408336270">00:14</login-time>
            -	    

            xo_attr is placed on the next container, instance, leaf, or leaf list that is emitted.

            -

            Since attributes are only emitted in XML, their use should be limited to meta-data and additional or redundant representations of data already emitted in other form.

            -
            -
            -

            -
            -3.2.2 
            -Flushing Output (xo_flush) -

            -

            libxo buffers data, both for performance and consistency, but also to allow some advanced features to work properly. At various times, the caller may wish to flush any data buffered within the library. The xo_flush() call is used for this:

            -
            -    void xo_flush (void);
            -    void xo_flush_h (xo_handle_t *xop);
            -	    

            Calling xo_flush also triggers the flush function associated with the handle. For the default handle, this is equivalent to "fflush(stdio);".

            +

            xo_attr is placed on the next container, instance, leaf, or leaf list that is emitted.

            +

            Since attributes are only emitted in XML, their use should be limited to meta-data and additional or redundant representations of data already emitted in other form.

            +Flushing Output (xo_flush) +

            +

            libxo buffers data, both for performance and consistency, but also to allow some advanced features to work properly. At various times, the caller may wish to flush any data buffered within the library. The xo_flush() call is used for this:

            +
            +    void xo_flush (void);
            +    void xo_flush_h (xo_handle_t *xop);
            +	    

            Calling xo_flush also triggers the flush function associated with the handle. For the default handle, this is equivalent to "fflush(stdio);".

            +
            +
            +

            +
            +3.2.4 
            Finishing Output (xo_finish)

            -

            When the program is ready to exit or close a handle, a call to xo_finish() is required. This flushes any buffered data, closes open libxo constructs, and completes any pending operations.

            -
            +

            When the program is ready to exit or close a handle, a call to xo_finish() is required. This flushes any buffered data, closes open libxo constructs, and completes any pending operations.

            +
                 int xo_finish (void);
                 int xo_finish_h (xo_handle_t *xop);
                 void xo_finish_atexit (void);
            -	    

            Calling this function is vital to the proper operation of libxo, especially for the non-TEXT output styles.

            -

            xo_finish_atexit is suitable for use with atexit(3).

            +

            Calling this function is vital to the proper operation of libxo, especially for the non-TEXT output styles.

            +

            xo_finish_atexit is suitable for use with atexit(3).

            @@ -24676,7 +24826,7 @@ jQuery(function ($) {

            libxo represents to types of hierarchy: containers and lists. A container appears once under a given parent where a list contains instances that can appear multiple times. A container is used to hold related fields and to give the data organization and scope.

            To create a container, use the xo_open_container and xo_close_container functions:

            -
            +
                 int xo_open_container (const char *name);
                 int xo_open_container_h (xo_handle_t *xop, const char *name);
                 int xo_open_container_hd (xo_handle_t *xop, const char *name);
            @@ -24690,7 +24840,7 @@ jQuery(function ($) {
             

            The close functions with the "_d" suffix are used in "Do The Right Thing" mode, where the name of the open containers, lists, and instances are maintained internally by libxo to allow the caller to avoid keeping track of the open container name.

            Use the XOF_WARN flag to generate a warning if the name given on the close does not match the current open container.

            For TEXT and HTML output, containers are not rendered into output text, though for HTML they are used when the XOF_XPATH flag is set.

            -
            +
                 EXAMPLE:
                    xo_open_container("system");
                    xo_emit("The host name is {:host-name}\n", hn);
            @@ -24707,7 +24857,7 @@ jQuery(function ($) {
             
             

            Lists are sequences of instances of homogeneous data objects. Two distinct levels of calls are needed to represent them in our output styles. Calls must be made to open and close a list, and for each instance of data in that list, calls must be make to open and close that instance.

            The name given to all calls must be identical, and it is strongly suggested that the name be singular, not plural, as a matter of style and usage expectations.

            -
            +
                 EXAMPLE:
                     xo_open_list("user");
                     for (i = 0; i < num_users; i++) {
            @@ -24776,11 +24926,11 @@ jQuery(function ($) {
             Parsing Command-line Arguments (xo_parse_args)
             
             

            The xo_parse_args() function is used to process a program's arguments. libxo-specific options are processed and removed from the argument list so the calling application does not need to process them. If successful, a new value for argc is returned. On failure, a message it emitted and -1 is returned.

            -
            +
                 argc = xo_parse_args(argc, argv);
                 if (argc < 0)
                     exit(EXIT_FAILURE);
            -	    

            Following the call to xo_parse_args, the application can process the remaining arguments in a normal manner. See Section 2.3 for a description of valid arguments.

            +

            Following the call to xo_parse_args, the application can process the remaining arguments in a normal manner. See Section 2.4 for a description of valid arguments.

            @@ -24789,7 +24939,7 @@ jQuery(function ($) { xo_set_program

            The xo_set_program function sets name of the program as reported by functions like xo_failure, xo_warn, xo_err, etc. The program name is initialized by xo_parse_args, but subsequent calls to xo_set_program can override this value.

            -
            +
                 xo_set_program(argv[0]);
             	    

            Note that the value is not copied, so the memory passed to xo_set_program (and xo_parse_args) must be maintained by the caller.

            @@ -24800,7 +24950,7 @@ jQuery(function ($) { xo_set_version

            The xo_set_version function records a version number to be emitted as part of the data for encoding styles (XML and JSON). This version number is suitable for tracking changes in the content, allowing a user of the data to discern which version of the data model is in use.

            -
            +
                  void xo_set_version (const char *version);
                  void xo_set_version_h (xo_handle_t *xop, const char *version);
             	    
            @@ -24813,7 +24963,7 @@ jQuery(function ($) {

            HTML data can include additional information in attributes that begin with "data‑". To enable this, three things must occur:

            First the application must build an array of xo_info_t structures, one per tag. The array must be sorted by name, since libxo uses a binary search to find the entry that matches names from format instructions.

            Second, the application must inform libxo about this information using the xo_set_info() call:

            -
            +
                 typedef struct xo_info_s {
                     const char *xi_name;    /* Name of the element */
                     const char *xi_type;    /* Type of field */
            @@ -24823,7 +24973,7 @@ jQuery(function ($) {
                 void xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count);
             	    

            Like other libxo calls, passing NULL for the handle tells libxo to use the default handle.

            If the count is -1, libxo will count the elements of infop, but there must be an empty element at the end. More typically, the number is known to the application:

            -
            +
                 xo_info_t info[] = {
                     { "in-stock", "number", "Number of items in stock" },
                     { "name", "string", "Name of the item" },
            @@ -24836,7 +24986,7 @@ jQuery(function ($) {
                 xo_set_info(NULL, info, info_count);
             	    

            Third, the emission of info must be triggered with the XOF_INFO flag using either the xo_set_flags() function or the "‑‑libxo=info" command line argument.

            The type and help values, if present, are emitted as the "data‑type" and "data‑help" attributes:

            -
            +
               <div class="data" data-tag="sku" data-type="string" 
                    data-help="Stock Keeping Unit">GRO-000-533</div>
             	    
            @@ -24847,7 +24997,7 @@ jQuery(function ($) { Memory Allocation

            The xo_set_allocator function allows libxo to be used in environments where the standard realloc() and free() functions are not available.

            -
            +
                 void xo_set_allocator (xo_realloc_func_t realloc_func,
                                        xo_free_func_t free_func);
             	    

            realloc_func should expect the same arguments as realloc(3) and return a pointer to memory following the same convention. free_func will receive the same argument as free(3) and should release it, as appropriate for the environment.

            @@ -24860,7 +25010,7 @@ jQuery(function ($) { LIBXO_OPTIONS

            The environment variable "LIBXO_OPTIONS" can be set to a string of options:

            -
            +
            @@ -24929,10 +25079,10 @@ jQuery(function ($) {
            Option Action

            For example, warnings can be enabled by:

            -
            +
                 % env LIBXO_OPTIONS=W my-app
             	    

            Complete HTML output can be generated with:

            -
            +
                 % env LIBXO_OPTIONS=HXI my-app
             	    

            Since environment variables are inherited, child processes will have the same options, which may be undesirable, making the use of the "‑‑libxo" option is preferable in most situations.

            @@ -24943,7 +25093,7 @@ jQuery(function ($) { Errors, Warnings, and Messages

            Many programs make use of the standard library functions err() and warn() to generate errors and warnings for the user. libxo wants to pass that information via the current output style, and provides compatible functions to allow this:

            -
            +
                 void xo_warn (const char *fmt, ...);
                 void xo_warnx (const char *fmt, ...);
                 void xo_warn_c (int code, const char *fmt, ...);
            @@ -24959,7 +25109,7 @@ jQuery(function ($) {
                 void xo_message_hcv (xo_handle_t *xop, int code, 
                                      const char *fmt, va_list vap);
             	    

            These functions display the program name, a colon, a formatted message based on the arguments, and then optionally a colon and an error message associated with either "errno" or the "code" parameter.

            -
            +
                 EXAMPLE:
                     if (open(filename, O_RDONLY) < 0)
                         xo_err(1, "cannot open file '%s'", filename);
            @@ -24971,7 +25121,7 @@ jQuery(function ($) {
             xo_error
             
             

            The xo_error function can be used for generic errors that should be reported over the handle, rather than to stderr. The xo_error function behaves like xo_err for TEXT and HTML output styles, but puts the error into XML or JSON elements:

            -
            +
                 EXAMPLE::
                     xo_error("Does not %s", "compute");
                 XML::
            @@ -24986,7 +25136,7 @@ jQuery(function ($) {
             xo_no_setlocale
             
             

            libxo automatically initializes the locale based on setting of the environment variables LC_CTYPE, LANG, and LC_ALL. The first of this list of variables is used and if none of the variables, the locale defaults to "UTF‑8". The caller may wish to avoid this behavior, and can do so by calling the xo_no_setlocale() function.

            -
            +
                 void xo_no_setlocale (void);
             	    
            @@ -25002,7 +25152,7 @@ jQuery(function ($) {

            https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers

            Use the Section 3.5.3.5() function to set the Enterprise ID, as needed.

            The message name should follow the conventions in Section 8.1.3, as should the fields within the message.

            -
            +
                 /* Both of these calls are optional */
                 xo_set_syslog_enterprise_id(32473);
                 xo_open_log("my-program", 0, LOG_DAEMON);
            @@ -25030,13 +25180,13 @@ jQuery(function ($) {
             Priority, Facility, and Flags
             
             

            The xo_syslog, xo_vsyslog, and xo_open_log functions accept a set of flags which provide the priority of the message, the source facility, and some additional features. These values are OR'd together to create a single integer argument:

            -
            +
                 xo_syslog(LOG_ERR | LOG_AUTH, "login-failed",
                          "Login failed; user '{:user}' from host '{:address}'",
                          user, addr);
             	    

            These values are defined in <syslog.h>.

            The priority value indicates the importance and potential impact of each message.

            -
            +
            @@ -25077,7 +25227,7 @@ jQuery(function ($) {
            Priority Description

            The facility value indicates the source of message, in fairly generic terms.

            -
            +
            @@ -25142,7 +25292,7 @@ jQuery(function ($) {
            Facility Description

            In addition to the values listed above, xo_open_log accepts a set of addition flags requesting specific behaviors.

            -
            +
            @@ -25175,7 +25325,7 @@ jQuery(function ($) {

            Use the xo_syslog function to generate syslog messages by calling it with a log priority and facility, a message name, a format string, and a set of arguments. The priority/facility argument are discussed above, as is the message name.

            The format string follows the same conventions as xo_emit's format string, with each field being rendered as an SD-PARAM pair.

            -
            +
                 xo_syslog(LOG_ERR, "poofd-missing-file",
                           "'{:filename}' not found: {:error/%m}", filename);
             
            @@ -25204,7 +25354,7 @@ jQuery(function ($) {
             xo_vsyslog
             
             

            xo_vsyslog is identical in function to xo_syslog, but takes the set of arguments using a va_list.

            -
            +
                 void my_log (const char *name, const char *fmt, ...)
                 {
                     va_list vap;
            @@ -25220,7 +25370,7 @@ jQuery(function ($) {
             xo_open_log
             
             

            xo_open_log functions similar to openlog(3), allowing customization of the program name, the log facility number, and the additional option flags described in Section 3.5.1.

            -
            +
                 void
                 xo_open_log (const char *ident, int logopt, int facility);
             	    
            @@ -25231,7 +25381,7 @@ jQuery(function ($) { xo_close_log

            xo_close_log functions similar to closelog(3), closing the log file and releasing any associated resources.

            -
            +
                 void
                 xo_close_log (void);
             	    
            @@ -25242,7 +25392,7 @@ jQuery(function ($) { xo_set_logmask

            xo_set_logmask function similar to setlogmask(3), restricting the set of generated log event to those whose associated bit is set in maskpri. Use LOG_MASK(pri) to find the appropriate bit, or LOG_UPTO(toppri) to create a mask for all priorities up to and including toppri.

            -
            +
                 int
                 xo_set_logmask (int maskpri);
             
            @@ -25257,7 +25407,7 @@ jQuery(function ($) {
             
             

            Use the xo_set_syslog_enterprise_id to supply a platform- or application-specific enterprise id. This value is used in any future syslog messages.

            Ideally, the operating system should supply a default value via the "kern.syslog.enterprise_id" sysctl value. Lacking that, the application should provide a suitable value.

            -
            +
                 void
                 xo_set_syslog_enterprise_id (unsigned short eid);
             	    

            Enterprise IDs are administered by IANA, the Internet Assigned Number Authority. The complete list is EIDs on their web site:

            @@ -25299,7 +25449,7 @@ jQuery(function ($) { Loading Encoders

            Encoders can be registered statically or discovered dynamically. Applications can choose to call the xo_encoder_register() function to explicitly register encoders, but more typically they are built as shared libraries, placed in the libxo/extensions directory, and loaded based on name. libxo looks for a file with the name of the encoder and an extension of ".enc". This can be a file or a symlink to the shared library file that supports the encoder.

            -
            +
                 % ls -1 lib/libxo/extensions/*.enc
                 lib/libxo/extensions/cbor.enc
                 lib/libxo/extensions/test.enc
            @@ -25311,7 +25461,7 @@ jQuery(function ($) {
             Encoder Initialization
             
             

            Each encoder must export a symbol used to access the library, which must have the following signature:

            -
            +
                 int xo_encoder_library_init (XO_ENCODER_INIT_ARGS);
             	    

            XO_ENCODER_INIT_ARGS is a macro defined in xo_encoder.h that defines an argument called "arg", a pointer of the type xo_encoder_init_args_t. This structure contains two fields:

            @@ -25329,7 +25479,7 @@ jQuery(function ($) { Operations

            The encoder API defines a set of operations representing the processing model of libxo. Content is formatted within libxo, and callbacks are made to the encoder's handler function when data is ready to be processed.

            -
            Flag Description
            +
            @@ -25416,7 +25566,7 @@ jQuery(function ($) {

            The "xo" utility allows command line access to the functionality of the libxo library. Using "xo", shell scripts can emit XML, JSON, and HTML using the same commands that emit text output.

            The style of output can be selected using a specific option: "‑X" for XML, "‑J" for JSON, "‑H" for HTML, or "‑T" for TEXT, which is the default. The "--style <style>" option can also be used. The LIBXO_OPTIONS environment variable can also be used to set the style, as well as other flags.

            The "xo" utility accepts a format string suitable for xo_emit() and a set of zero or more arguments used to supply data for that string.

            -
            +
                 xo "The {k:name} weighs {:weight/%d} pounds.\n" fish 6
             
               TEXT:
            @@ -25436,7 +25586,7 @@ jQuery(function ($) {
                   <div class="text"> pounds.</div>
                 </div>
             	    

            The "--wrap <path>" option can be used to wrap emitted content in a specific hierarchy. The path is a set of hierarchical names separated by the '/' character.

            -
            +
                 xo --wrap top/a/b/c '{:tag}' value
             
               XML:
            @@ -25460,7 +25610,7 @@ jQuery(function ($) {
                   }
                 }
             	    

            The "--open <path>" and "--close <path>" can be used to emit hierarchical information without the matching close and open tag. This allows a shell script to emit open tags, data, and then close tags. The "‑‑depth" option may be used to set the depth for indentation. The "‑‑leading‑xpath" may be used to prepend data to the XPath values used for HTML output style.

            -
            +
                 #!/bin/sh
                 xo --open top/data
                 xo --depth 2 '{tag}' value
            @@ -25489,7 +25639,7 @@ jQuery(function ($) {
             Command Line Options
             
             

            Usage: xo [options] format [fields]

            -
            +
               --close <path>        Close tags for the given path
               --depth <num>         Set the depth for pretty printing
               --help                Display this help text
            @@ -25513,7 +25663,7 @@ jQuery(function ($) {
             4.2 
             Example
             
            -
            +
               % xo 'The {:product} is {:status}\n' stereo "in route"
               The stereo is in route
               % ./xo/xo -p -X 'The {:product} is {:status}\n' stereo "in route"
            @@ -25530,7 +25680,7 @@ jQuery(function ($) {
             
             

            xolint is a tool for reporting common mistakes in format strings in source code that invokes xo_emit(). It allows these errors to be diagnosed at build time, rather than waiting until runtime.

            xolint takes the one or more C files as arguments, and reports and errors, warning, or informational messages as needed.

            -
            Operation Meaning (Base function)
            +
            @@ -25571,7 +25721,7 @@ jQuery(function ($) {
            Option Meaning

            The output message will contain the source filename and line number, the class of the message, the message, and, if -p is given, the line that contains the error:

            -
            +
                 % xolint.pl -t xolint.c
                 xolint.c: 16: error: anchor format should be "%d"
                 16         xo_emit("{[:/%s}");
            @@ -25587,7 +25737,7 @@ jQuery(function ($) {
             
             

            xohtml is a tool for turning the output of libxo-enabled commands into html files suitable for display in modern HTML web browsers. It can be used to test and debug HTML output, as well as to make the user ache to escape the world of 70s terminal devices.

            xohtml is given a command, either on the command line or via the "‑c" option. If not command is given, standard input is used. The command's output is wrapped in HTML tags, with references to supporting CSS and Javascript files, and written to standard output or the file given in the "‑f" option. The "‑b" option can be used to provide an alternative base path for the support files.

            -
            +
            @@ -25619,7 +25769,7 @@ jQuery(function ($) {

            The "xopo" utility filters ".pot" files generated by the "xgettext" utility to remove formatting information suitable for use with the "{G:}" modifier. This means that when the developer changes the formatting portion of the field definitions, or the fields modifiers, the string passed to gettext(3) is unchanged, avoiding the expense of updating any existing translation files (".po" files).

            The syntax for the xopo command is one of two forms; it can be used as a filter for processing a .po or .pot file, rewriting the "msgid" strings with a simplified message string. In this mode, the input is either standard input or a file given by the "‑f" option, and the output is either standard output or a file given by the "‑o" option.

            In the second mode, a simple message given using the "‑s" option on the command, and the simplified version of that message is printed on stdout.

            -
            Option Meaning
            +
            @@ -25639,7 +25789,7 @@ jQuery(function ($) {
            Option Meaning
            -
            +
                 EXAMPLE:
                     % xopo -s "There are {:count/%u} {:event/%.6s} events\n"
                     There are {:count} {:event} events\n
            @@ -25687,9 +25837,9 @@ jQuery(function ($) {
             8.1.1 
             Can you share the history of libxo?
             
            -

            In 2001, we added an XML API to the JUNOS operating system, which is built on top of FreeBSD. Eventually this API became standardized as the NETCONF API (RFC 6241). As part of this effort, we modified many FreeBSD utilities to emit XML, typically via a "‑X" switch. The results were mixed. The cost of maintaining this code, updating it and carrying it were non-trivial, and contributed to our expense (and the associated delay) with upgrading the version of FreeBSD on which each release of JUNOS is based.

            -

            A recent (2014) effort within JUNOS aims at removing our modifications to the underlying FreeBSD code as a means of reducing the expense and delay. JUNOS is structured to have system components generate XML that is rendered by the CLI (think: login shell) into human-readable text. This allows the API to use the same plumbing as the CLI, and ensures that all components emit XML, and that it is emitted with knowledge of the consumer of that XML, yielding an API that have no incremental cost or feature delay.

            -

            libxo is an effort to mix the best aspects of the JUNOS strategy into FreeBSD in a seemless way, allowing commands to make printf-like output calls without needing to care how the output is rendered.

            +

            In 2001, we added an XML API to the JUNOS operating system, which is built on top of FreeBSD. Eventually this API became standardized as the NETCONF API (RFC 6241). As part of this effort, we modified many FreeBSD utilities to emit XML, typically via a "‑X" switch. The results were mixed. The cost of maintaining this code, updating it, and carrying it were non-trivial, and contributed to our expense (and the associated delay) with upgrading the version of FreeBSD on which each release of JUNOS is based.

            +

            A recent (2014) effort within JUNOS aims at removing our modifications to the underlying FreeBSD code as a means of reducing the expense and delay in tracking HEAD. JUNOS is structured to have system components generate XML that is rendered by the CLI (think: login shell) into human-readable text. This allows the API to use the same plumbing as the CLI, and ensures that all components emit XML, and that it is emitted with knowledge of the consumer of that XML, yielding an API that have no incremental cost or feature delay.

            +

            libxo is an effort to mix the best aspects of the JUNOS strategy into FreeBSD in a seemless way, allowing commands to make printf-like output calls with a single code path.

            @@ -25698,7 +25848,7 @@ jQuery(function ($) { Did the complex semantics of format strings evolve over time?

            The history is both long and short: libxo's functionality is based on what JUNOS does in a data modeling language called ODL (output definition language). In JUNOS, all subcomponents generate XML, which is feed to the CLI, where data from the ODL files tell is how to render that XML into text. ODL might had a set of tags like:

            -
            +
                  tag docsis-state {
                      help "State of the DOCSIS interface";
                      type string;
            @@ -25777,7 +25927,7 @@ jQuery(function ($) {
             
            Reuse existing field names
            Nothing's worse than writing expressions like:
            -
            +
                 if ($src1/process[pid == $pid]/name == 
                     $src2/proc-table/proc-list
                                /proc-entry[process-id == $pid]/proc-name) {
            @@ -25789,7 +25939,7 @@ jQuery(function ($) {
             
            Use containment as scoping
            In the previous example, all the names are prefixed with "proc‑", which is redundant given that they are nested under the process table.
            Think about your users
            -
            Have empathy for your users, choosing clear and useful fields that contain clear and useful data. You may need to augment the display content with xo_attr() calls (Section 3.2.1) or "{e:}" fields (Section 2.2.2.3) to make the data useful.
            +
            Have empathy for your users, choosing clear and useful fields that contain clear and useful data. You may need to augment the display content with xo_attr() calls (Section 3.2.2) or "{e:}" fields (Section 2.2.2.4) to make the data useful.
            Don't use an arbitrary number postfix
            What does "errors2" mean? No one will know. "errors‑after‑restart" would be a better choice. Think of your users, and think of the future. If you make "errors2", the next guy will happily make "errors3" and before you know it, someone will be asking what's the difference between errors37 and errors63.
            Be consistent, uniform, unsurprising, and predictable
            @@ -25838,10 +25988,10 @@ jQuery(function ($) { 'A percent sign appearing in text is a literal'

            The message "A percent sign appearing in text is a literal" can be caused by code like:

            -
            +
                 xo_emit("cost: %d", cost);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{L:cost}: {:cost/%d}", cost);
             	    

            This can be a bit surprising and could be a field that was not properly converted to a libxo-style format string.

            @@ -25852,10 +26002,10 @@ jQuery(function ($) { 'Unknown long name for role/modifier'

            The message "Unknown long name for role/modifier" can be caused by code like:

            -
            +
                 xo_emit("{,humanization:value}", value);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{,humanize:value}", value);
             	    

            The hn-* modifiers (hn-decimal, hn-space, hn-1000) are only valid for fields with the {h:} modifier.

            @@ -25867,10 +26017,10 @@ jQuery(function ($) {

            The message "Last character before field definition is a field type" can be caused by code like:

            A common typo:

            -
            +
                 xo_emit("{T:Min} T{:Max}");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{T:Min} {T:Max}");
             	    

            Twiddling the "{" and the field role is a common typo.

            @@ -25881,10 +26031,10 @@ jQuery(function ($) { 'Encoding format uses different number of arguments'

            The message "Encoding format uses different number of arguments" can be caused by code like:

            -
            +
                 xo_emit("{:name/%6.6s %%04d/%s}", name, number);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{:name/%6.6s %04d/%s-%d}", name, number);
             	    

            Both format should consume the same number of arguments off the stack

            @@ -25895,10 +26045,10 @@ jQuery(function ($) { 'Only one field role can be used'

            The message "Only one field role can be used" can be caused by code like:

            -
            +
                 xo_emit("{LT:Max}");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{T:Max}");
             	    
            @@ -25908,10 +26058,10 @@ jQuery(function ($) { 'Potential missing slash after C, D, N, L, or T with format'

            The message "Potential missing slash after C, D, N, L, or T with format" can be caused by code like:

            -
            +
                 xo_emit("{T:%6.6s}\n", "Max");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{T:/%6.6s}\n", "Max");
             	    

            The "%6.6s" will be a literal, not a field format. While it's possibly valid, it's likely a missing "/".

            @@ -25922,7 +26072,7 @@ jQuery(function ($) { 'An encoding format cannot be given (roles: DNLT)'

            The message "An encoding format cannot be given (roles: DNLT)" can be caused by code like:

            -
            +
                 xo_emit("{T:Max//%s}", "Max");
             	    

            Fields with the C, D, N, L, and T roles are not emitted in the 'encoding' style (JSON, XML), so an encoding format would make no sense.

            @@ -25933,7 +26083,7 @@ jQuery(function ($) { 'Format cannot be given when content is present (roles: CDLN)'

            The message "Format cannot be given when content is present (roles: CDLN)" can be caused by code like:

            -
            +
                 xo_emit("{N:Max/%6.6s}", "Max");
             	    

            Fields with the C, D, L, or N roles can't have both static literal content ("{L:Label}") and a format ("{L:/%s}"). This error will also occur when the content has a backslash in it, like "{N:Type of I/O}"; backslashes should be escaped, like "{N:Type of I\\/O}". Note the double backslash, one for handling 'C' strings, and one for libxo.

            @@ -25944,10 +26094,10 @@ jQuery(function ($) { 'Field has color without fg- or bg- (role: C)'

            The message "Field has color without fg- or bg- (role: C)" can be caused by code like:

            -
            +
                 xo_emit("{C:green}{:foo}{C:}", x);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{C:fg-green}{:foo}{C:}", x);
             	    

            Colors must be prefixed by either "fg‑" or "bg‑".

            @@ -25958,10 +26108,10 @@ jQuery(function ($) { 'Field has invalid color or effect (role: C)'

            The message "Field has invalid color or effect (role: C)" can be caused by code like:

            -
            +
                 xo_emit("{C:fg-purple,bold}{:foo}{C:gween}", x);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{C:fg-red,bold}{:foo}{C:fg-green}", x);
             	    

            The list of colors and effects are limited. The set of colors includes default, black, red, green, yellow, blue, magenta, cyan, and white, which must be prefixed by either "fg‑" or "bg‑". Effects are limited to bold, no-bold, underline, no-underline, inverse, no-inverse, normal, and reset. Values must be separated by commas.

            @@ -25972,10 +26122,10 @@ jQuery(function ($) { 'Field has humanize modifier but no format string'

            The message "Field has humanize modifier but no format string" can be caused by code like:

            -
            +
                 xo_emit("{h:value}", value);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{h:value/%d}", value);
             	    

            Humanization is only value for numbers, which are not likely to use the default format ("%s").

            @@ -25986,10 +26136,10 @@ jQuery(function ($) { 'Field has hn-* modifier but not 'h' modifier'

            The message "Field has hn-* modifier but not 'h' modifier" can be caused by code like:

            -
            +
                 xo_emit("{,hn-1000:value}", value);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{h,hn-1000:value}", value);
             	    

            The hn-* modifiers (hn-decimal, hn-space, hn-1000) are only valid for fields with the {h:} modifier.

            @@ -26000,10 +26150,10 @@ jQuery(function ($) { 'Value field must have a name (as content)")'

            The message "Value field must have a name (as content)")" can be caused by code like:

            -
            +
                 xo_emit("{:/%s}", "value");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{:tag-name/%s}", "value");
             	    

            The field name is used for XML and JSON encodings. These tags names are static and must appear directly in the field descriptor.

            @@ -26014,10 +26164,10 @@ jQuery(function ($) { 'Use hyphens, not underscores, for value field name'

            The message "Use hyphens, not underscores, for value field name" can be caused by code like:

            -
            +
                 xo_emit("{:no_under_scores}", "bad");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{:no-under-scores}", "bad");
             	    

            Use of hyphens is traditional in XML, and the XOF_UNDERSCORES flag can be used to generate underscores in JSON, if desired. But the raw field name should use hyphens.

            @@ -26028,10 +26178,10 @@ jQuery(function ($) { 'Value field name cannot start with digit'

            The message "Value field name cannot start with digit" can be caused by code like:

            -
            +
                 xo_emit("{:10-gig/}");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{:ten-gig/}");
             	    

            XML element names cannot start with a digit.

            @@ -26042,10 +26192,10 @@ jQuery(function ($) { 'Value field name should be lower case'

            The message "Value field name should be lower case" can be caused by code like:

            -
            +
                 xo_emit("{:WHY-ARE-YOU-SHOUTING}", "NO REASON");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{:why-are-you-shouting}", "no reason");
             	    

            Lower case is more civilized. Even TLAs should be lower case to avoid scenarios where the differences between "XPath" and "Xpath" drive your users crazy. Lower case rules the seas.

            @@ -26056,10 +26206,10 @@ jQuery(function ($) { 'Value field name should be longer than two characters'

            The message "Value field name should be longer than two characters" can be caused by code like:

            -
            +
                 xo_emit("{:x}", "mumble");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{:something-meaningful}", "mumble");
             	    

            Field names should be descriptive, and it's hard to be descriptive in less than two characters. Consider your users and try to make something more useful. Note that this error often occurs when the field type is placed after the colon ("{:T/%20s}"), instead of before it ("{T:/20s}").

            @@ -26070,10 +26220,10 @@ jQuery(function ($) { 'Value field name contains invalid character'

            The message "Value field name contains invalid character" can be caused by code like:

            -
            +
                 xo_emit("{:cost-in-$$/%u}", 15);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{:cost-in-dollars/%u}", 15);
             	    

            An invalid character is often a sign of a typo, like "{:]}" instead of "{]:}". Field names are restricted to lower-case characters, digits, and hyphens.

            @@ -26084,10 +26234,10 @@ jQuery(function ($) { 'decoration field contains invalid character'

            The message "decoration field contains invalid character" can be caused by code like:

            -
            +
                 xo_emit("{D:not good}");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{D:((}{:good}{D:))}", "yes");
             	    

            This is minor, but fields should use proper roles. Decoration fields are meant to hold punctuation and other characters used to decorate the content, typically to make it more readable to human readers.

            @@ -26098,10 +26248,10 @@ jQuery(function ($) { 'Anchor content should be decimal width'

            The message "Anchor content should be decimal width" can be caused by code like:

            -
            +
                 xo_emit("{[:mumble}");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{[:32}");
             	    

            Anchors need an integer value to specify the width of the set of anchored fields. The value can be positive (for left padding/right justification) or negative (for right padding/left justification) and can appear in either the start or stop anchor field descriptor.

            @@ -26112,10 +26262,10 @@ jQuery(function ($) { 'Anchor format should be "%d"'

            The message "Anchor format should be "%d"" can be caused by code like:

            -
            +
                 xo_emit("{[:/%s}");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{[:/%d}");
             	    

            Anchors only grok integer values, and if the value is not static, if must be in an 'int' argument, represented by the "%d" format. Anything else is an error.

            @@ -26126,10 +26276,10 @@ jQuery(function ($) { 'Anchor cannot have both format and encoding format")'

            The message "Anchor cannot have both format and encoding format")" can be caused by code like:

            -
            +
                 xo_emit("{[:32/%d}");
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{[:32}");
             	    

            Anchors can have a static value or argument for the width, but cannot have both.

            @@ -26140,10 +26290,10 @@ jQuery(function ($) { 'Max width only valid for strings'

            The message "Max width only valid for strings" can be caused by code like:

            -
            +
                 xo_emit("{:tag/%2.4.6d}", 55);
             	    

            This code should be replaced with code like:

            -
            +
                 xo_emit("{:tag/%2.6d}", 55);
             	    

            libxo allows a true 'max width' in addition to the traditional printf-style 'max number of bytes to use for input'. But this is supported only for string values, since it makes no sense for non-strings. This error may occur from a typo, like "{:tag/%6..6d}" where only one period should be used.

            @@ -26183,7 +26333,7 @@ jQuery(function ($) {

            libxo is open source, under a new BSD license. Source code is available on github, as are recent releases. To get the most current release, please visit:

            https://github.com/Juniper/libxo/releases

            After downloading and untarring the source code, building involves the following steps:

            -
            +
                 sh bin/setup.sh
                 cd build
                 ../configure
            @@ -26192,7 +26342,7 @@ jQuery(function ($) {
                 sudo make install
             	    

            libxo uses a distinct "build" directory to keep generated files separated from source files.

            Use "../configure --help" to display available configuration options, which include the following:

            -
            +
               --enable-warnings      Turn on compiler warnings
               --enable-debug         Turn on debugging
               --enable-text-only     Turn on text-only rendering
            @@ -26212,7 +26362,7 @@ jQuery(function ($) {
             9.3 
             Howto: Convert command line applications
             
            -
            +
                 How do I convert an existing command line application?
             	    

            There are three basic steps for converting command line application to use libxo.

            @@ -26236,10 +26386,10 @@ jQuery(function ($) { Setting up the context

            To use libxo, you'll need to include the "xo.h" header file in your source code files:

            -
            +
                 #include <libxo/xo.h>
             	    

            In your main() function, you'll need to call xo_parse_args to handling argument parsing (Section 3.4.1). This function removes libxo-specific arguments the program's argv and returns either the number of remaining arguments or -1 to indicate an error.

            -
            +
                 int main (int argc, char **argv)
                 {
                     argc = xo_parse_args(argc, argv);
            @@ -26247,8 +26397,8 @@ jQuery(function ($) {
                         return argc;
                     ....
                 }
            -	    

            At the bottom of your main(), you'll need to call xo_finish() to complete output processing for the default handle (Section 2.5). libxo provides the xo_finish_atexit function that is suitable for use with the atexit(3) function.

            -
            +	    

            At the bottom of your main(), you'll need to call xo_finish() to complete output processing for the default handle (Section 3.1). libxo provides the xo_finish_atexit function that is suitable for use with the atexit(3) function.

            +
                 atexit(xo_finish_atexit);
             	    
            @@ -26258,20 +26408,20 @@ jQuery(function ($) { Converting printf Calls

            The second task is inspecting code for printf(3) calls and replacing them with xo_emit() calls. The format strings are similar in task, but libxo format strings wrap output fields in braces. The following two calls produce identical text output:

            -
            +
                 printf("There are %d %s events\n", count, etype);
                 xo_emit("There are {:count/%d} {:event} events\n", count, etype);
             	    

            "count" and "event" are used as names for JSON and XML output. The "count" field uses the format "%d" and "event" uses the default "%s" format. Both are "value" roles, which is the default role.

            Since text outside of output fields is passed verbatim, other roles are less important, but their proper use can help make output more useful. The "note" and "label" roles allow HTML output to recognize the relationship between text and the associated values, allowing appropriate "hover" and "onclick" behavior. Using the "units" role allows the presentation layer to perform conversions when needed. The "warning" and "error" roles allows use of color and font to draw attention to warnings. The "padding" role makes the use of vital whitespace more clear (Section 2.2.1.6).

            The "title" role indicates the headings of table and sections. This allows HTML output to use CSS to make this relationship more obvious.

            -
            +
                 printf("Statistics:\n");
                 xo_emit("{T:Statistics}:\n");
             	    

            The "color" roles controls foreground and background colors, as well as effects like bold and underline (see Section 2.2.1.1).

            -
            +
                 xo_emit("{C:bold}required{C:}\n");
             	    

            Finally, the start- and stop-anchor roles allow justification and padding over multiple fields (see Section 2.2.1.10).

            -
            +
                 snprintf(buf, sizeof(buf), "(%u/%u/%u)", min, ave, max);
                 printf("%30s", buf);
             
            @@ -26285,7 +26435,7 @@ jQuery(function ($) {
             Creating Hierarchy
             
             

            Text output doesn't have any sort of hierarchy, but XML and JSON require this. Typically applications use indentation to represent these relationship:

            -
            +
                 printf("table %d\n", tnum);
                 for (i = 0; i < tmax; i++) {
                     printf("    %s %d\n", table[i].name, table[i].size);
            @@ -26303,7 +26453,7 @@ jQuery(function ($) {
             	    

            The open and close list functions are used before and after the list, and the open and close instance functions are used before and after each instance with in the list.

            Typically these developer looks for a "for" loop as an indication of where to put these calls.

            In addition, the open and close container functions allow for organization levels of hierarchy.

            -
            +
                 printf("Paging information:\n");
                 printf("    Free:      %lu\n", free);
                 printf("    Active:    %lu\n", active);
            @@ -26322,7 +26472,7 @@ jQuery(function ($) {
             Converting Error Functions
             
             

            libxo provides variants of the standard error and warning functions, err(3) and warn(3). There are two variants, one for putting the errors on standard error, and the other writes the errors and warnings to the handle using the appropriate encoding style:

            -
            +
                 err(1, "cannot open output file: %s", file);
             
                 xo_err(1, "cannot open output file: %s", file);
            @@ -26340,12 +26490,12 @@ jQuery(function ($) {
             9.5 
            Howto: Internationalization (i18n) -
            +
                 How do I use libxo to support internationalization?
             	    

            libxo allows format and field strings to be used a keys into message catalogs to enable translation into a user's native language by invoking the standard gettext(3) functions.

            gettext setup is a bit complicated: text strings are extracted from source files into "portable object template" (.pot) files using the "xgettext" command. For each language, this template file is used as the source for a message catalog in the "portable object" (.po) format, which are translated by hand and compiled into "machine object" (.mo) files using the "msgfmt" command. The .mo files are then typically installed in the /usr/share/locale or /opt/local/share/locale directories. At run time, the user's language settings are used to select a .mo file which is searched for matching messages. Text strings in the source code are used as keys to look up the native language strings in the .mo file.

            Since the xo_emit format string is used as the key into the message catalog, libxo removes unimportant field formatting and modifiers from the format string before use so that minor formatting changes will not impact the expensive translation process. We don't want a developer change such as changing "/%06d" to "/%08d" to force hand inspection of all .po files. The simplified version can be generated for a single message using the "xopo -s <text>" command, or an entire .pot can be translated using the "xopo -f <input> -o <output>" command.

            -
            +
                 EXAMPLE:
                     % xopo -s "There are {:count/%u} {:event/%.6s} events\n"
                     There are {:count} {:event} events\n
            @@ -26378,7 +26528,7 @@ jQuery(function ($) {
                     sudo cp po/my_lang/LC_MESSAGES/foo.mo \
                             /opt/local/share/locale/my_lang/LC_MESSAGE/
             	    

            Once these steps are complete, you can use the "gettext" command to test the message catalog:

            -
            +
                 gettext -d foo -e "some text"
             	    

            Section Contents:

            @@ -26396,7 +26546,7 @@ jQuery(function ($) {
          • The "{p:}" modifier looks for a pluralized version of the field.

          Together these three flags allows a single function call to give native language support, as well as libxo's normal XML, JSON, and HTML support.

          -
          +
               printf(gettext("Received %zu %s from {g:server} server\n"),
                      counter, ngettext("byte", "bytes", counter),
                      gettext("web"));
          @@ -26404,17 +26554,17 @@ jQuery(function ($) {
               xo_emit("{G:}Received {:received/%zu} {Ngp:byte,bytes} "
                       "from {g:server} server\n", counter, "web");
           	    

          libxo will see the "{G:}" role and will first simplify the format string, removing field formats and modifiers.

          -
          +
               "Received {:received} {N:byte,bytes} from {:server} server\n"
           	    

          libxo calls gettext(3) with that string to get a localized version. If your language were Pig Latin, the result might look like:

          -
          +
               "Eceivedray {:received} {N:byte,bytes} omfray "
                          "{:server} erversay\n"
           	    

          Note the field names do not change and they should not be translated. The contents of the note ("byte,bytes") should also not be translated, since the "g" modifier will need the untranslated value as the key for the message catalog.

          The field "{g:server}" requests the rendered value of the field be translated using gettext(3). In this example, "web" would be used.

          The field "{Ngp:byte,bytes}" shows an example of plural form using the "p" modifier with the "g" modifier. The base singular and plural forms appear inside the field, separated by a comma. At run time, libxo uses the previous field's numeric value to decide which form to use by calling ngettext(3).

          If a domain name is needed, it can be supplied as the content of the {G:} role. Domain names remain in use throughout the format string until cleared with another domain name.

          -
          +
               printf(dgettext("dns", "Host %s not found: %d(%s)\n"),
                   name, errno, dgettext("strerror", strerror(errno)));
           
          @@ -26439,7 +26589,7 @@ jQuery(function ($) {
           Unit Test
           
           

          Here is the unit test example:

          -
          +
               int
               main (int argc, char **argv)
               {
          @@ -26532,7 +26682,7 @@ jQuery(function ($) {
                   return 0;
               }
           	    

          Text output:

          -
          +
               % ./testxo --libxo text
               Item 'gum':
                  Total sold: 1412.0
          @@ -26565,7 +26715,7 @@ jQuery(function ($) {
                  On order: 1
                  SKU: GRO-000-533
           	    

          JSON output:

          -
          +
               % ./testxo --libxo json,pretty
               "top": {
                 "data": {
          @@ -26620,7 +26770,7 @@ jQuery(function ($) {
                 }
               }
           	    

          XML output:

          -
          +
               % ./testxo --libxo pretty,xml
               <top>
                 <data>
          @@ -26671,7 +26821,7 @@ jQuery(function ($) {
                 </data>
               </top>
           	    

          HMTL output:

          -
          +
               % ./testxo --libxo pretty,html
               <div class="line">
                 <div class="label">Item</div>
          @@ -26866,7 +27016,7 @@ jQuery(function ($) {
                 <div class="data" data-tag="sku">GRO-000-533</div>
               </div>
           	    

          HTML output with xpath and info flags:

          -
          +
               % ./testxo --libxo pretty,html,xpath,info
               <div class="line">
                 <div class="label">Item</div>
          diff --git a/doc/libxo.txt b/doc/libxo.txt
          index 1e7acc7984be..ba63702920c5 100644
          --- a/doc/libxo.txt
          +++ b/doc/libxo.txt
          @@ -699,25 +699,26 @@ XOF_WARN is set, a warning will be generated.
           Field modifiers are flags which modify the way content emitted for
           particular output styles:
           
          -|---+---------------+-------------------------------------------------|
          -| M | Name          | Description                                     |
          -|---+---------------+-------------------------------------------------|
          -| c | colon         | A colon (":") is appended after the label       |
          -| d | display       | Only emit field for display styles (text/HTML)  |
          -| e | encoding      | Only emit for encoding styles (XML/JSON)        |
          -| g | gettext       | Call gettext on field's render content          |
          -| h | humanize (hn) | Format large numbers in human-readable style    |
          -|   | hn-space      | Humanize: Place space between numeric and unit  |
          -|   | hn-decimal    | Humanize: Add a decimal digit, if number < 10   |
          -|   | hn-1000       | Humanize: Use 1000 as divisor instead of 1024   |
          -| k | key           | Field is a key, suitable for XPath predicates   |
          -| l | leaf-list     | Field is a leaf-list                            |
          -| n | no-quotes     | Do not quote the field when using JSON style    |
          -| p | plural        | Gettext: Use comma-separated plural form        |
          -| q | quotes        | Quote the field when using JSON style           |
          -| t | trim          | Trim leading and trailing whitespace            |
          -| w | white         | A blank (" ") is appended after the label       |
          -|---+---------------+-------------------------------------------------|
          +|---+---------------+--------------------------------------------------|
          +| M | Name          | Description                                      |
          +|---+---------------+--------------------------------------------------|
          +| a | argument      | The content appears as a 'const char *' argument |
          +| c | colon         | A colon (":") is appended after the label        |
          +| d | display       | Only emit field for display styles (text/HTML)   |
          +| e | encoding      | Only emit for encoding styles (XML/JSON)         |
          +| g | gettext       | Call gettext on field's render content           |
          +| h | humanize (hn) | Format large numbers in human-readable style     |
          +|   | hn-space      | Humanize: Place space between numeric and unit   |
          +|   | hn-decimal    | Humanize: Add a decimal digit, if number < 10    |
          +|   | hn-1000       | Humanize: Use 1000 as divisor instead of 1024    |
          +| k | key           | Field is a key, suitable for XPath predicates    |
          +| l | leaf-list     | Field is a leaf-list                             |
          +| n | no-quotes     | Do not quote the field when using JSON style     |
          +| p | plural        | Gettext: Use comma-separated plural form         |
          +| q | quotes        | Quote the field when using JSON style            |
          +| t | trim          | Trim leading and trailing whitespace             |
          +| w | white         | A blank (" ") is appended after the label        |
          +|---+---------------+--------------------------------------------------|
           
           Roles and modifiers can also use more verbose names, when preceeded by
           a comma.  For example, the modifier string "Lwc" (or "L,white,colon")
          @@ -727,6 +728,27 @@ modifier string "Vkq" (or ":key,quote") means the field has a value
           role (the default role), that it is a key for the current instance,
           and that the value should be quoted when encoded for JSON.
           
          +**** The Argument Modifier ({a:})
          +
          +The argument modifier indicates that the content of the field
          +descriptor will be placed as a UTF-8 string (const char *) argument
          +within the xo_emit parameters.
          +
          +    EXAMPLE:
          +      xo_emit("{La:} {a:}\n", "Label text", "label", "value");
          +    TEXT:
          +      Label text value
          +    JSON:
          +      "label": "value"
          +    XML:
          +      
          +
          +The argument modifier allows field names for value fields to be passed
          +on the stack, avoiding the need to build a field descriptor using
          +snprintf.  For many field roles, the argument modifier is not needed,
          +since those roles have specific mechanisms for arguments, such as
          +"{C:fg-%s}".
          +
           **** The Colon Modifier ({c:})
           
           The colon modifier appends a single colon to the data value:
          @@ -907,6 +929,21 @@ needed, but often this needs to be controlled by the caller.
               JSON:
                 "year": "2014"
           
          +The heuristic is based on the format; if the format uses any of the
          +following conversion specifiers, then no quotes are used:
          +
          +    d i o u x X D O U e E f F g G a A c C p
          +
          +**** The Trim Modifier ({t:})
          +
          +The trim modifier removes any leading or trailing whitespace from
          +the value.
          +
          +    EXAMPLE:
          +      xo_emit("{t:description}", "   some  input   ");
          +    JSON:
          +      "description": "some input"
          +
           **** The White Space Modifier ({w:})
           
           The white space modifier appends a single space to the data value:
          @@ -1029,6 +1066,24 @@ LANG, or LC_ALL environment varibles.  The first of this list of
           variables is used and if none of the variables are set, the locale
           defaults to "UTF-8".
           
          +libxo will convert these arguments as needed to either UTF-8 (for XML,
          +JSON, and HTML styles) or locale-based strings for display in text
          +style.
          +
          +   xo_emit("Alll strings are utf-8 content {:tag/%ls}",
          +           L"except for wide strings");
          +
          +"%S" is equivalent to "%ls".
          +
          +|--------+-----------------+-------------------------------|
          +| Format | Argument Type   | Argument Contents             |
          +|--------+-----------------+-------------------------------|
          +| %s     | const char *    | UTF-8 string                  |
          +| %S     | const char *    | UTF-8 string (alias for '%s') |
          +| %ls    | const wchar_t * | Wide character UNICODE string |
          +| %hs    | const char *    | locale-based string           |
          +|--------+-----------------+-------------------------------|
          +
           For example, a function is passed a locale-base name, a hat size,
           and a time value.  The hat size is formatted in a UTF-8 (ASCII)
           string, and the time value is formatted into a wchar_t string.
          @@ -1163,6 +1218,53 @@ variants might be wise.
           | xo_emit_errc     | xo_emit_errc_p         |
           |------------------+------------------------|
           
          +*** Retaining Parsed Format Information @retain@
          +
          +libxo can retain the parsed internal information related to the given
          +format string, allowing subsequent xo_emit calls, the retained
          +information is used, avoiding repetitive parsing of the format string.
          +
          +    SYNTAX:
          +      int xo_emit_f(xo_emit_flags_t flags, const char fmt, ...);
          +    EXAMPLE:
          +      xo_emit_f(XOEF_RETAIN, "{:some/%02d}{:thing/%-6s}{:fancy}\n",
          +                     some, thing, fancy);
          +
          +To retain parsed format information, use the XOEF_RETAIN flag to the
          +xo_emit_f() function.  A complete set of xo_emit_f functions exist to
          +match all the xo_emit function signatures (with handles, varadic
          +argument, and printf-like flags):
          +
          +|------------------+------------------------|
          +| Function         | Flags Equivalent       |
          +|------------------+------------------------|
          +| xo_emit_hv       | xo_emit_hvf            |
          +| xo_emit_h        | xo_emit_hf             |
          +| xo_emit          | xo_emit_f              |
          +| xo_emit_hvp      | xo_emit_hvfp           |
          +| xo_emit_hp       | xo_emit_hfp            |
          +| xo_emit_p        | xo_emit_fp             |
          +|------------------+------------------------|
          +
          +The format string must be immutable across multiple calls to xo_emit_f(),
          +since the library retains the string.  Typically this is done by using
          +static constant strings, such as string literals. If the string is not
          +immutable, the XOEF_RETAIN flag must not be used.
          +
          +The functions xo_retain_clear() and xo_retain_clear_all() release
          +internal information on either a single format string or all format
          +strings, respectively.  Neither is required, but the library will
          +retain this information until it is cleared or the process exits.
          +
          +    const char *fmt = "{:name}  {:count/%d}\n";
          +    for (i = 0; i < 1000; i++) {
          +        xo_open_instance("item");
          +        xo_emit_f(XOEF_RETAIN, fmt, name[i], count[i]);
          +    }
          +    xo_retain_clear(fmt);
          +
          +The retained information is kept as thread-specific data.
          +
           *** Example
           
           In this example, the value for the number of items in stock is emitted:
          @@ -1196,46 +1298,6 @@ penultimate line to:
                     data-type="number"
                     data-help="Number of items in stock">144
           
          -** Command-line Arguments
          -
          -libxo uses command line options to trigger rendering behavior.  The
          -following options are recognised:
          -
          -- --libxo 
          -- --libxo=
          -- --libxo:
          -
          -Options is a comma-separated list of tokens that correspond to output
          -styles, flags, or features:
          -
          -|-------------+-------------------------------------------------------|
          -| Token       | Action                                                |
          -|-------------+-------------------------------------------------------|
          -| color       | Enable colors/effects for display styles (TEXT, HTML) |
          -| dtrt        | Enable "Do The Right Thing" mode                      |
          -| html        | Emit HTML output                                      |
          -| indent=xx   | Set the indentation level                             |
          -| info        | Add info attributes (HTML)                            |
          -| json        | Emit JSON output                                      |
          -| keys        | Emit the key attribute for keys (XML)                 |
          -| log-gettext | Log (via stderr) each gettext(3) string lookup        |
          -| log-syslog  | Log (via stderr) each syslog message (via xo_syslog)  |
          -| no-humanize | Ignore the {h:} modifier (TEXT, HTML)                 |
          -| no-locale   | Do not initialize the locale setting                  |
          -| no-top      | Do not emit a top set of braces (JSON)                |
          -| not-first   | Pretend the 1st output item was not 1st (JSON)        |
          -| pretty      | Emit pretty-printed output                            |
          -| text        | Emit TEXT output                                      |
          -| underscores | Replace XML-friendly "-"s with JSON friendly "_"s e   |
          -| units       | Add the 'units' (XML) or 'data-units (HTML) attribute |
          -| warn        | Emit warnings when libxo detects bad calls            |
          -| warn-xml    | Emit warnings in XML                                  |
          -| xml         | Emit XML output                                       |
          -| xpath       | Add XPath expressions (HTML)                          |
          -|-------------+-------------------------------------------------------|
          -
          -The brief options are detailed in ^LIBXO_OPTIONS^.
          -
           ** Representing Hierarchy
           
           For XML and JSON, individual fields appear inside hierarchies which
          @@ -1382,20 +1444,81 @@ properly.
                   xo_close_marker("fish-guts");
               }
           
          +** Command-line Arguments
          +
          +libxo uses command line options to trigger rendering behavior.  The
          +following options are recognised:
          +
          +- --libxo 
          +- --libxo=
          +- --libxo:
          +
          +Programs using libxo are expecting to call the xo_parse_args function
          +to parse these arguments.  See ^xo_parse_args^ for details.
          +
          +Options is a comma-separated list of tokens that correspond to output
          +styles, flags, or features:
          +
          +|-------------+-------------------------------------------------------|
          +| Token       | Action                                                |
          +|-------------+-------------------------------------------------------|
          +| color       | Enable colors/effects for display styles (TEXT, HTML) |
          +| dtrt        | Enable "Do The Right Thing" mode                      |
          +| html        | Emit HTML output                                      |
          +| indent=xx   | Set the indentation level                             |
          +| info        | Add info attributes (HTML)                            |
          +| json        | Emit JSON output                                      |
          +| keys        | Emit the key attribute for keys (XML)                 |
          +| log-gettext | Log (via stderr) each gettext(3) string lookup        |
          +| log-syslog  | Log (via stderr) each syslog message (via xo_syslog)  |
          +| no-humanize | Ignore the {h:} modifier (TEXT, HTML)                 |
          +| no-locale   | Do not initialize the locale setting                  |
          +| no-retain   | Prevent retaining formatting information              |
          +| no-top      | Do not emit a top set of braces (JSON)                |
          +| not-first   | Pretend the 1st output item was not 1st (JSON)        |
          +| pretty      | Emit pretty-printed output                            |
          +| retain      | Force retaining formatting information                |
          +| text        | Emit TEXT output                                      |
          +| underscores | Replace XML-friendly "-"s with JSON friendly "_"s e   |
          +| units       | Add the 'units' (XML) or 'data-units (HTML) attribute |
          +| warn        | Emit warnings when libxo detects bad calls            |
          +| warn-xml    | Emit warnings in XML                                  |
          +| xml         | Emit XML output                                       |
          +| xpath       | Add XPath expressions (HTML)                          |
          +|-------------+-------------------------------------------------------|
          +
          +The brief options are detailed in ^LIBXO_OPTIONS^.
          +
          +* The libxo API
          +
          +This section gives details about the functions in libxo, how to call
          +them, and the actions they perform.
          +
           ** Handles @handles@
           
           libxo uses "handles" to control its rendering functionality.  The
           handle contains state and buffered data, as well as callback functions
           to process data.
           
          -A default handle is used when a NULL is passed to functions accepting
          -a handle.  This handle is initialized to write its data to stdout
          -using the default style of text (XO_STYLE_TEXT).
          +Handles give an abstraction for libxo that encapsulates the state of a
          +stream of output.  Handles have the data type "xo_handle_t" and are
          +opaque to the caller.
           
          -For the convenience of callers, the libxo library includes handle-less
          -functions that implicitly use the default handle.  Any function that
          -takes a handle will use the default handle is a value of NULL is
          -passed in place of a valid handle.
          +The library has a default handle that is automatically initialized.
          +By default, this handle will send text style output (XO_STYLE_TEXT) to
          +standard output.  The xo_set_style and xo_set_flags functions can be
          +used to change this behavior.
          +
          +For the typical command that is generating output on standard output,
          +there is no need to create an explicit handle, but they are available
          +when needed, e.g., for daemons that generate multiple streams of
          +output.
          +
          +Many libxo functions take a handle as their first parameter; most that
          +do not use the default handle.  Any function taking a handle can be
          +passed NULL to access the default handle.  For the convenience of
          +callers, the libxo library includes handle-less functions that
          +implicitly use the default handle.
           
           For example, the following are equivalent:
           
          @@ -1404,46 +1527,6 @@ For example, the following are equivalent:
           
           Handles are created using xo_create() and destroy using xo_destroy().
           
          -** UTF-8
          -
          -All strings for libxo must be UTF-8.  libxo will handle turning them
          -into locale-based strings for display to the user.
          -
          -The only exception is argument formatted using the "%ls" format, which
          -require a wide character string (wchar_t *) as input.  libxo will
          -convert these arguments as needed to either UTF-8 (for XML, JSON, and
          -HTML styles) or locale-based strings for display in text style.
          -
          -   xo_emit("Alll strings are utf-8 content {:tag/%ls}",
          -           L"except for wide strings");
          -
          -"%S" is equivalent to "%ls".
          -
          -* The libxo API
          -
          -This section gives details about the functions in libxo, how to call
          -them, and the actions they perform.
          -
          -** Handles
          -
          -Handles give an abstraction for libxo that encapsulates the state of a
          -stream of output.  Handles have the data type "xo_handle_t" and are
          -opaque to the caller.
          -
          -The library has a default handle that is automatically initialized.
          -By default, this handle will send text style output to standard output.
          -The xo_set_style and xo_set_flags functions can be used to change this
          -behavior.
          -
          -Many libxo functions take a handle as their first parameter; most that
          -do not use the default handle.  Any function taking a handle can
          -be passed NULL to access the default handle.
          -
          -For the typical command that is generating output on standard output,
          -there is no need to create an explicit handle, but they are available
          -when needed, e.g., for daemons that generate multiple streams of
          -output.
          -
           *** xo_create
           
           A handle can be allocated using the xo_create() function:
          @@ -1653,11 +1736,34 @@ string, since an inappropriate cast can ruin your day.  The vap
           argument to xo_emit_hv() points to a variable argument list that can
           be used to retrieve arguments via va_arg().
           
          +*** Single Field Emitting Functions (xo_emit_field) @xo_emit_field@
          +
          +The following functions can also make output, but only make a single
          +field at a time:
          +
          +    int xo_emit_field_hv (xo_handle_t *xop, const char *rolmod,
          +                  const char *contents, const char *fmt, 
          +		  const char *efmt, va_list vap);
          +
          +    int xo_emit_field_h (xo_handle_t *xop, const char *rolmod, 
          +                 const char *contents, const char *fmt,
          +		 const char *efmt, ...);
          +
          +    int xo_emit_field (const char *rolmod, const char *contents,
          +	         const char *fmt, const char *efmt, ...);
          +
          +These functions are intended to avoid the scenario where one
          +would otherwise need to compose a format descriptors using
          +snprintf().  The individual parts of the format descriptor are
          +passed in distinctly.
          +
          +    xo_emit("T", "Host name is ", NULL, NULL);
          +    xo_emit("V", "host-name", NULL, NULL, host-name);
          +
           *** Attributes (xo_attr) @xo_attr@
           
           The xo_attr() function emits attributes for the XML output style.
           
          -
               int xo_attr (const char *name, const char *fmt, ...);
               int xo_attr_h (xo_handle_t *xop, const char *name, 
                              const char *fmt, ...);
          @@ -2555,23 +2661,23 @@ In 2001, we added an XML API to the JUNOS operating system, which is
           built on top of FreeBSD.  Eventually this API became standardized as
           the NETCONF API (RFC 6241).  As part of this effort, we modified many
           FreeBSD utilities to emit XML, typically via a "-X" switch.  The
          -results were mixed.  The cost of maintaining this code, updating it
          +results were mixed.  The cost of maintaining this code, updating it,
           and carrying it were non-trivial, and contributed to our expense (and
           the associated delay) with upgrading the version of FreeBSD on which
           each release of JUNOS is based.
           
           A recent (2014) effort within JUNOS aims at removing our modifications
           to the underlying FreeBSD code as a means of reducing the expense and
          -delay.  JUNOS is structured to have system components generate XML
          -that is rendered by the CLI (think: login shell) into human-readable
          -text.  This allows the API to use the same plumbing as the CLI, and
          -ensures that all components emit XML, and that it is emitted with
          -knowledge of the consumer of that XML, yielding an API that have no
          -incremental cost or feature delay.
          +delay in tracking HEAD.  JUNOS is structured to have system components
          +generate XML that is rendered by the CLI (think: login shell) into
          +human-readable text.  This allows the API to use the same plumbing as
          +the CLI, and ensures that all components emit XML, and that it is
          +emitted with knowledge of the consumer of that XML, yielding an API
          +that have no incremental cost or feature delay.
           
           libxo is an effort to mix the best aspects of the JUNOS strategy into
           FreeBSD in a seemless way, allowing commands to make printf-like
          -output calls without needing to care how the output is rendered.
          +output calls with a single code path.
           
           *** Did the complex semantics of format strings evolve over time?
           
          diff --git a/encoder/cbor/enc_cbor.c b/encoder/cbor/enc_cbor.c
          index 513063fb1508..7c0a1d33f932 100644
          --- a/encoder/cbor/enc_cbor.c
          +++ b/encoder/cbor/enc_cbor.c
          @@ -135,7 +135,7 @@ cbor_encode_uint (xo_buffer_t *xbp, uint64_t minor, unsigned limit)
               char *bp = xbp->xb_curp;
               int i, m;
           
          -    if (minor > (1UL<<32)) {
          +    if (minor > (1ULL << 32)) {
           	*bp++ |= CBOR_LEN64;
           	m = 64;
           
          diff --git a/libxo-config.in b/libxo-config.in
          index 3dbb7d41a364..f08f2340ecdb 100644
          --- a/libxo-config.in
          +++ b/libxo-config.in
          @@ -77,34 +77,34 @@ while test $# -gt 0; do
           	;;
           
               --cflags)
          -       	echo -I@LIBXO_INCLUDEDIR@ @LIBXO_CFLAGS@
          +       	echo -I@XO_INCLUDEDIR@ @XO_CFLAGS@
                  	;;
           
           
               --share)
          -       	echo @LIBXO_SHAREDIR@
          +       	echo @XO_SHAREDIR@
                  	;;
           
               --bindir)
          -       	echo @LIBXO_BINDIR@
          +       	echo @XO_BINDIR@
                  	;;
           
               --libdir)
          -       	echo @LIBXO_LIBDIR@
          +       	echo @XO_LIBDIR@
                  	;;
           
           
               --libs)
                   if [ "`uname`" = "Linux" ]
           	then
          -	    if [ "@LIBXO_LIBDIR@" = "-L/usr/lib" -o "@LIBXO_LIBDIR@" = "-L/usr/lib64" ]
          +	    if [ "@XO_LIBDIR@" = "-L/usr/lib" -o "@XO_LIBDIR@" = "-L/usr/lib64" ]
           	    then
          -		echo @LIBXO_LIBS@ 
          +		echo @XO_LIBS@ 
           	    else
          -		echo -L@LIBXO_LIBDIR@ @LIBXO_LIBS@ 
          +		echo -L@XO_LIBDIR@ @XO_LIBS@ 
           	    fi
           	else
          -	    echo -L@LIBXO_LIBDIR@ @LIBXO_LIBS@ @WIN32_EXTRA_LIBADD@
          +	    echo -L@XO_LIBDIR@ @XO_LIBS@
           	fi
                  	;;
           
          diff --git a/libxo/libxo.c b/libxo/libxo.c
          index bae810f179c7..194a0962b428 100644
          --- a/libxo/libxo.c
          +++ b/libxo/libxo.c
          @@ -19,7 +19,8 @@
            *   http://juniper.github.io/libxo/libxo-manual.html
            *
            * For first time readers, the core bits of code to start looking at are:
          - * - xo_do_emit() -- the central function of the library
          + * - xo_do_emit() -- parse and emit a set of fields
          + * - xo_do_emit_fields -- the central function of the library
            * - xo_do_format_field() -- handles formatting a single field
            * - xo_transiton() -- the state machine that keeps things sane
            * and of course the "xo_handle_t" data structure, which carries all
          @@ -120,6 +121,7 @@
           
           const char xo_version[] = LIBXO_VERSION;
           const char xo_version_extra[] = LIBXO_VERSION_EXTRA;
          +static const char xo_default_format[] = "%s";
           
           #ifndef UNUSED
           #define UNUSED __attribute__ ((__unused__))
          @@ -338,6 +340,7 @@ typedef unsigned long xo_xff_flags_t;
           #define XFF_GT_FIELD	(1<<19) /* Call gettext() on a field */
           
           #define XFF_GT_PLURAL	(1<<20)	/* Call dngettext to find plural form */
          +#define XFF_ARGUMENT	(1<<21)	/* Content provided via argument */
           
           /* Flags to turn off when we don't want i18n processing */
           #define XFF_GT_FLAGS (XFF_GT_FIELD | XFF_GT_PLURAL)
          @@ -1046,7 +1049,7 @@ xo_is_utf8 (char ch)
               return (ch & 0x80);
           }
           
          -static int
          +static inline int
           xo_utf8_to_wc_len (const char *buf)
           {
               unsigned b = (unsigned char) *buf;
          @@ -1105,9 +1108,13 @@ xo_buf_utf8_len (xo_handle_t *xop, const char *buf, int bufsiz)
            * bits we pull off the first character is dependent on the length,
            * but we put 6 bits off all other bytes.
            */
          -static wchar_t
          +static inline wchar_t
           xo_utf8_char (const char *buf, int len)
           {
          +    /* Most common case: singleton byte */
          +    if (len == 1)
          +	return (unsigned char) buf[0];
          +
               int i;
               wchar_t wc;
               const unsigned char *cp = (const unsigned char *) buf;
          @@ -1281,6 +1288,195 @@ xo_data_escape (xo_handle_t *xop, const char *str, int len)
               xo_buf_escape(xop, &xop->xo_data, str, len, 0);
           }
           
          +#ifdef LIBXO_NO_RETAIN
          +/*
          + * Empty implementations of the retain logic
          + */
          +
          +void
          +xo_retain_clear_all (void)
          +{
          +    return;
          +}
          +
          +void
          +xo_retain_clear (const char *fmt UNUSED)
          +{
          +    return;
          +}
          +static void
          +xo_retain_add (const char *fmt UNUSED, xo_field_info_t *fields UNUSED,
          +		unsigned num_fields UNUSED)
          +{
          +    return;
          +}
          +
          +static int
          +xo_retain_find (const char *fmt UNUSED, xo_field_info_t **valp UNUSED,
          +		 unsigned *nump UNUSED)
          +{
          +    return -1;
          +}
          +
          +#else /* !LIBXO_NO_RETAIN */
          +/*
          + * Retain: We retain parsed field definitions to enhance performance,
          + * especially inside loops.  We depend on the caller treating the format
          + * strings as immutable, so that we can retain pointers into them.  We
          + * hold the pointers in a hash table, so allow quick access.  Retained
          + * information is retained until xo_retain_clear is called.
          + */
          +
          +/*
          + * xo_retain_entry_t holds information about one retained set of
          + * parsed fields.
          + */
          +typedef struct xo_retain_entry_s {
          +    struct xo_retain_entry_s *xre_next; /* Pointer to next (older) entry */
          +    unsigned long xre_hits;		 /* Number of times we've hit */
          +    const char *xre_format;		 /* Pointer to format string */
          +    unsigned xre_num_fields;		 /* Number of fields saved */
          +    xo_field_info_t *xre_fields;	 /* Pointer to fields */
          +} xo_retain_entry_t;
          +
          +/*
          + * xo_retain_t holds a complete set of parsed fields as a hash table.
          + */
          +#ifndef XO_RETAIN_SIZE
          +#define XO_RETAIN_SIZE 6
          +#endif /* XO_RETAIN_SIZE */
          +#define RETAIN_HASH_SIZE (1<> 4) & (((1 << 24) - 1)));
          +
          +    val = (val ^ 61) ^ (val >> 16);
          +    val = val + (val << 3);
          +    val = val ^ (val >> 4);
          +    val = val * 0x3a8f05c5;	/* My large prime number */
          +    val = val ^ (val >> 15);
          +    val &= RETAIN_HASH_SIZE - 1;
          +
          +    return val;
          +}	
          +
          +/*
          + * Walk all buckets, clearing all retained entries
          + */
          +void
          +xo_retain_clear_all (void)
          +{
          +    int i;
          +    xo_retain_entry_t *xrep, *next;
          +
          +    for (i = 0; i < RETAIN_HASH_SIZE; i++) {
          +	for (xrep = xo_retain.xr_bucket[i]; xrep; xrep = next) {
          +	    next = xrep->xre_next;
          +	    xo_free(xrep);
          +	}
          +	xo_retain.xr_bucket[i] = NULL;
          +    }
          +    xo_retain_count = 0;
          +}
          +
          +/*
          + * Walk all buckets, clearing all retained entries
          + */
          +void
          +xo_retain_clear (const char *fmt)
          +{
          +    xo_retain_entry_t **xrepp;
          +    unsigned hash = xo_retain_hash(fmt);
          +
          +    for (xrepp = &xo_retain.xr_bucket[hash]; *xrepp;
          +	 xrepp = &(*xrepp)->xre_next) {
          +	if ((*xrepp)->xre_format == fmt) {
          +	    *xrepp = (*xrepp)->xre_next;
          +	    xo_retain_count -= 1;
          +	    return;
          +	}
          +    }
          +}
          +
          +/*
          + * Search the hash for an entry matching 'fmt'; return it's fields.
          + */
          +static int
          +xo_retain_find (const char *fmt, xo_field_info_t **valp, unsigned *nump)
          +{
          +    if (xo_retain_count == 0)
          +	return -1;
          +
          +    unsigned hash = xo_retain_hash(fmt);
          +    xo_retain_entry_t *xrep;
          +
          +    for (xrep = xo_retain.xr_bucket[hash]; xrep != NULL;
          +	 xrep = xrep->xre_next) {
          +	if (xrep->xre_format == fmt) {
          +	    *valp = xrep->xre_fields;
          +	    *nump = xrep->xre_num_fields;
          +	    xrep->xre_hits += 1;
          +	    return 0;
          +	}
          +    }
          +
          +    return -1;
          +}
          +
          +static void
          +xo_retain_add (const char *fmt, xo_field_info_t *fields, unsigned num_fields)
          +{
          +    unsigned hash = xo_retain_hash(fmt);
          +    xo_retain_entry_t *xrep;
          +    unsigned sz = sizeof(*xrep) + (num_fields + 1) * sizeof(*fields);
          +    xo_field_info_t *xfip;
          +
          +    xrep = xo_realloc(NULL, sz);
          +    if (xrep == NULL)
          +	return;
          +
          +    xfip = (xo_field_info_t *) &xrep[1];
          +    memcpy(xfip, fields, num_fields * sizeof(*fields));
          +
          +    bzero(xrep, sizeof(*xrep));
          +
          +    xrep->xre_format = fmt;
          +    xrep->xre_fields = xfip;
          +    xrep->xre_num_fields = num_fields;
          +
          +    /* Record the field info in the retain bucket */
          +    xrep->xre_next = xo_retain.xr_bucket[hash];
          +    xo_retain.xr_bucket[hash] = xrep;
          +    xo_retain_count += 1;
          +}
          +
          +#endif /* !LIBXO_NO_RETAIN */
          +
           /*
            * Generate a warning.  Normally, this is a text message written to
            * standard error.  If the XOF_WARN_XML flag is set, then we generate
          @@ -1574,6 +1770,19 @@ xo_message_hcv (xo_handle_t *xop, int code, const char *fmt, va_list vap)
           	break;
               }
           
          +    switch (xo_style(xop)) {
          +    case XO_STYLE_HTML:
          +	if (XOIF_ISSET(xop, XOIF_DIV_OPEN)) {
          +	    static char div_close[] = "";
          +	    XOIF_CLEAR(xop, XOIF_DIV_OPEN);
          +	    xo_data_append(xop, div_close, sizeof(div_close) - 1);
          +
          +	    if (XOF_ISSET(xop, XOF_PRETTY))
          +		xo_data_append(xop, "\n", 1);
          +	}
          +	break;
          +    }
          +
               (void) xo_flush_h(xop);
           }
           
          @@ -1679,6 +1888,39 @@ xo_create_to_file (FILE *fp, xo_style_t style, xo_xof_flags_t flags)
               return xop;
           }
           
          +/**
          + * Set the default handler to output to a file.
          + * @xop libxo handle
          + * @fp FILE pointer to use
          + */
          +int
          +xo_set_file_h (xo_handle_t *xop, FILE *fp)
          +{
          +    xop = xo_default(xop);
          +
          +    if (fp == NULL) {
          +	xo_failure(xop, "xo_set_file: NULL fp");
          +	return -1;
          +    }
          +
          +    xop->xo_opaque = fp;
          +    xop->xo_write = xo_write_to_file;
          +    xop->xo_close = xo_close_file;
          +    xop->xo_flush = xo_flush_file;
          +
          +    return 0;
          +}
          +
          +/**
          + * Set the default handler to output to a file.
          + * @fp FILE pointer to use
          + */
          +int
          +xo_set_file (FILE *fp)
          +{
          +    return xo_set_file_h(NULL, fp);
          +}
          +
           /**
            * Release any resources held by the handle.
            * @xop XO handle to alter (or NULL for default handle)
          @@ -1824,9 +2066,11 @@ static xo_mapping_t xo_xof_names[] = {
               { XOF_LOG_SYSLOG, "log-syslog" },
               { XOF_NO_HUMANIZE, "no-humanize" },
               { XOF_NO_LOCALE, "no-locale" },
          +    { XOF_RETAIN_NONE, "no-retain" },
               { XOF_NO_TOP, "no-top" },
               { XOF_NOT_FIRST, "not-first" },
               { XOF_PRETTY, "pretty" },
          +    { XOF_RETAIN_ALL, "retain" },
               { XOF_UNDERSCORES, "underscores" },
               { XOF_UNITS, "units" },
               { XOF_WARN, "warn" },
          @@ -3613,10 +3857,9 @@ xo_format_text (xo_handle_t *xop, const char *str, int len)
           }
           
           static void
          -xo_format_title (xo_handle_t *xop, xo_field_info_t *xfip)
          +xo_format_title (xo_handle_t *xop, xo_field_info_t *xfip,
          +		 const char *str, unsigned len)
           {
          -    const char *str = xfip->xfi_content;
          -    unsigned len = xfip->xfi_clen;
               const char *fmt = xfip->xfi_format;
               unsigned flen = xfip->xfi_flen;
               xo_xff_flags_t flags = xfip->xfi_flags;
          @@ -4083,10 +4326,9 @@ xo_format_value (xo_handle_t *xop, const char *name, int nlen,
           }
           
           static void
          -xo_set_gettext_domain (xo_handle_t *xop, xo_field_info_t *xfip)
          +xo_set_gettext_domain (xo_handle_t *xop, xo_field_info_t *xfip,
          +		       const char *str, unsigned len)
           {
          -    const char *str = xfip->xfi_content;
          -    unsigned len = xfip->xfi_clen;
               const char *fmt = xfip->xfi_format;
               unsigned flen = xfip->xfi_flen;
           
          @@ -4335,13 +4577,13 @@ xo_colors_enabled (xo_handle_t *xop UNUSED)
           }
           
           static void
          -xo_colors_handle_text (xo_handle_t *xop UNUSED, xo_colors_t *newp)
          +xo_colors_handle_text (xo_handle_t *xop, xo_colors_t *newp)
           {
               char buf[BUFSIZ];
               char *cp = buf, *ep = buf + sizeof(buf);
               unsigned i, bit;
               xo_colors_t *oldp = &xop->xo_colors;
          -    const char *code;
          +    const char *code = NULL;
           
               /*
                * Start the buffer with an escape.  We don't want to add the '['
          @@ -4460,10 +4702,9 @@ xo_colors_handle_html (xo_handle_t *xop, xo_colors_t *newp)
           }
           
           static void
          -xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip)
          +xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip,
          +		  const char *str, unsigned len)
           {
          -    const char *str = xfip->xfi_content;
          -    unsigned len = xfip->xfi_clen;
               const char *fmt = xfip->xfi_format;
               unsigned flen = xfip->xfi_flen;
           
          @@ -4534,10 +4775,9 @@ xo_format_colors (xo_handle_t *xop, xo_field_info_t *xfip)
           }
           
           static void
          -xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip)
          +xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip,
          +		 const char *str, unsigned len)
           {
          -    const char *str = xfip->xfi_content;
          -    unsigned len = xfip->xfi_clen;
               const char *fmt = xfip->xfi_format;
               unsigned flen = xfip->xfi_flen;
               xo_xff_flags_t flags = xfip->xfi_flags;
          @@ -4589,10 +4829,9 @@ xo_format_units (xo_handle_t *xop, xo_field_info_t *xfip)
           }
           
           static int
          -xo_find_width (xo_handle_t *xop, xo_field_info_t *xfip)
          +xo_find_width (xo_handle_t *xop, xo_field_info_t *xfip,
          +	       const char *str, unsigned len)
           {
          -    const char *str = xfip->xfi_content;
          -    unsigned len = xfip->xfi_clen;
               const char *fmt = xfip->xfi_format;
               unsigned flen = xfip->xfi_flen;
           
          @@ -4639,7 +4878,8 @@ xo_anchor_clear (xo_handle_t *xop)
            * format it when the end anchor tag is seen.
            */
           static void
          -xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip)
          +xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip,
          +		 const char *str, unsigned len)
           {
               if (xo_style(xop) != XO_STYLE_TEXT && xo_style(xop) != XO_STYLE_HTML)
           	return;
          @@ -4656,11 +4896,12 @@ xo_anchor_start (xo_handle_t *xop, xo_field_info_t *xfip)
                * Now we find the width, if possible.  If it's not there,
                * we'll get it on the end anchor.
                */
          -    xop->xo_anchor_min_width = xo_find_width(xop, xfip);
          +    xop->xo_anchor_min_width = xo_find_width(xop, xfip, str, len);
           }
           
           static void
          -xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip)
          +xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip,
          +		 const char *str, unsigned len)
           {
               if (xo_style(xop) != XO_STYLE_TEXT && xo_style(xop) != XO_STYLE_HTML)
           	return;
          @@ -4672,7 +4913,7 @@ xo_anchor_stop (xo_handle_t *xop, xo_field_info_t *xfip)
           
               XOIF_CLEAR(xop, XOIF_UNITS_PENDING);
           
          -    int width = xo_find_width(xop, xfip);
          +    int width = xo_find_width(xop, xfip, str, len);
               if (width == 0)
           	width = xop->xo_anchor_min_width;
           
          @@ -4787,6 +5028,7 @@ static xo_mapping_t xo_role_names[] = {
           #define XO_ROLE_NEWLINE	'\n'
           
           static xo_mapping_t xo_modifier_names[] = {
          +    { XFF_ARGUMENT, "argument" },
               { XFF_COLON, "colon" },
               { XFF_COMMA, "comma" },
               { XFF_DISPLAY_ONLY, "display" },
          @@ -4858,6 +5100,7 @@ xo_count_fields (xo_handle_t *xop UNUSED, const char *fmt)
            *   '[': start a section of anchored text
            *   ']': end a section of anchored text
            * The following modifiers are also supported:
          + *   'a': content is provided via argument (const char *), not descriptor
            *   'c': flag: emit a colon after the label
            *   'd': field is only emitted for display styles (text and html)
            *   'e': field is only emitted for encoding styles (xml and json)
          @@ -4884,7 +5127,7 @@ xo_parse_roles (xo_handle_t *xop, const char *fmt,
               xo_xff_flags_t flags = 0;
               uint8_t fnum = 0;
           
          -    for (sp = basep; sp; sp++) {
          +    for (sp = basep; sp && *sp; sp++) {
           	if (*sp == ':' || *sp == '/' || *sp == '}')
           	    break;
           
          @@ -4961,6 +5204,10 @@ xo_parse_roles (xo_handle_t *xop, const char *fmt,
           	    fnum = (fnum * 10) + (*sp - '0');
           	    break;
           
          +	case 'a':
          +	    flags |= XFF_ARGUMENT;
          +	    break;
          +
           	case 'c':
           	    flags |= XFF_COLON;
           	    break;
          @@ -5133,7 +5380,6 @@ static int
           xo_parse_fields (xo_handle_t *xop, xo_field_info_t *fields,
           		 unsigned num_fields, const char *fmt)
           {
          -    static const char default_format[] = "%s";
               const char *cp, *sp, *ep, *basep;
               unsigned field = 0;
               xo_field_info_t *xfip = fields;
          @@ -5267,12 +5513,12 @@ xo_parse_fields (xo_handle_t *xop, xo_field_info_t *fields,
           	xfip->xfi_next = ++sp;
           
           	/* If we have content, then we have a default format */
          -	if (xfip->xfi_clen || format) {
          +	if (xfip->xfi_clen || format || (xfip->xfi_flags & XFF_ARGUMENT)) {
           	    if (format) {
           		xfip->xfi_format = format;
           		xfip->xfi_flen = flen;
           	    } else if (xo_role_wants_default_format(xfip->xfi_ftype)) {
          -		xfip->xfi_format = default_format;
          +		xfip->xfi_format = xo_default_format;
           		xfip->xfi_flen = 2;
           	    }
           	}
          @@ -5568,9 +5814,8 @@ xo_gettext_combine_formats (xo_handle_t *xop, const char *fmt UNUSED,
            * Summary: i18n aighn't cheap.
            */
           static const char *
          -xo_gettext_build_format (xo_handle_t *xop UNUSED,
          -			 xo_field_info_t *fields UNUSED,
          -			 int this_field UNUSED,
          +xo_gettext_build_format (xo_handle_t *xop,
          +			 xo_field_info_t *fields, int this_field,
           			 const char *fmt, char **new_fmtp)
           {
               if (xo_style_is_encoding(xop))
          @@ -5686,17 +5931,22 @@ xo_gettext_rebuild_content (xo_handle_t *xop UNUSED,
           #endif /* HAVE_GETTEXT */
           
           /*
          - * The central function for emitting libxo output.
          + * Emit a set of fields.  This is really the core of libxo.
            */
           static int
          -xo_do_emit (xo_handle_t *xop, const char *fmt)
          +xo_do_emit_fields (xo_handle_t *xop, xo_field_info_t *fields,
          +		   unsigned max_fields, const char *fmt)
           {
               int gettext_inuse = 0;
               int gettext_changed = 0;
               int gettext_reordered = 0;
          +    unsigned ftype;
          +    xo_xff_flags_t flags;
               xo_field_info_t *new_fields = NULL;
          -
          +    xo_field_info_t *xfip;
          +    unsigned field;
               int rc = 0;
          +
               int flush = XOF_ISSET(xop, XOF_FLUSH);
               int flush_line = XOF_ISSET(xop, XOF_FLUSH_LINE);
               char *new_fmt = NULL;
          @@ -5704,20 +5954,6 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
               if (XOIF_ISSET(xop, XOIF_REORDER) || xo_style(xop) == XO_STYLE_ENCODER)
           	flush_line = 0;
           
          -    xop->xo_columns = 0;	/* Always reset it */
          -    xop->xo_errno = errno;	/* Save for "%m" */
          -
          -    unsigned max_fields = xo_count_fields(xop, fmt), field;
          -    xo_field_info_t fields[max_fields], *xfip;
          -
          -    bzero(fields, max_fields * sizeof(fields[0]));
          -
          -    if (xo_parse_fields(xop, fields, max_fields, fmt))
          -	return -1;		/* Warning already displayed */
          -    
          -    unsigned ftype;
          -    xo_xff_flags_t flags;
          -
               /*
                * Some overhead for gettext; if the fields in the msgstr returned
                * by gettext are reordered, then we need to record start and end
          @@ -5745,6 +5981,18 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
           		min_fstart = field;
           	}
           
          +	const char *content = xfip->xfi_content;
          +	int clen = xfip->xfi_clen;
          +
          +	if (flags & XFF_ARGUMENT) {
          +	    /*
          +	     * Argument flag means the content isn't given in the descriptor,
          +	     * but as a UTF-8 string ('const char *') argument in xo_vap.
          +	     */
          +	    content = va_arg(xop->xo_vap, char *);
          +	    clen = content ? strlen(content) : 0;
          +	}
          +
           	if (ftype == XO_ROLE_NEWLINE) {
           	    xo_line_close(xop);
           	    if (flush_line && xo_flush_h(xop) < 0)
          @@ -5773,15 +6021,15 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
           	}
           
           	if (ftype == 'V')
          -	    xo_format_value(xop, xfip->xfi_content, xfip->xfi_clen,
          +	    xo_format_value(xop, content, clen,
           			    xfip->xfi_format, xfip->xfi_flen,
           			    xfip->xfi_encoding, xfip->xfi_elen, flags);
           	else if (ftype == '[')
          -	    xo_anchor_start(xop, xfip);
          +	    xo_anchor_start(xop, xfip, content, clen);
           	else if (ftype == ']')
          -	    xo_anchor_stop(xop, xfip);
          +	    xo_anchor_stop(xop, xfip, content, clen);
           	else if (ftype == 'C')
          -	    xo_format_colors(xop, xfip);
          +	    xo_format_colors(xop, xfip, content, clen);
           
           	else if (ftype == 'G') {
           	    /*
          @@ -5792,7 +6040,7 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
           	     * Since gettext returns strings in a static buffer, we make
           	     * a copy in new_fmt.
           	     */
          -	    xo_set_gettext_domain(xop, xfip);
          +	    xo_set_gettext_domain(xop, xfip, content, clen);
           
           	    if (!gettext_inuse) { /* Only translate once */
           		gettext_inuse = 1;
          @@ -5843,17 +6091,17 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
           	    }
           	    continue;
           
          -	} else  if (xfip->xfi_clen || xfip->xfi_format) {
          +	} else  if (clen || xfip->xfi_format) {
           
           	    const char *class_name = xo_class_name(ftype);
           	    if (class_name)
           		xo_format_content(xop, class_name, xo_tag_name(ftype),
          -				  xfip->xfi_content, xfip->xfi_clen,
          +				  content, clen,
           				  xfip->xfi_format, xfip->xfi_flen, flags);
           	    else if (ftype == 'T')
          -		xo_format_title(xop, xfip);
          +		xo_format_title(xop, xfip, content, clen);
           	    else if (ftype == 'U')
          -		xo_format_units(xop, xfip);
          +		xo_format_units(xop, xfip, content, clen);
           	    else
           		xo_failure(xop, "unknown field type: '%c'", ftype);
           	}
          @@ -5884,7 +6132,7 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
               if (flush && !XOIF_ISSET(xop, XOIF_ANCHOR)) {
           	if (xo_write(xop) < 0) 
           	    rc = -1;		/* Report failure */
          -	else if (xop->xo_flush && xop->xo_flush(xop->xo_opaque) < 0)
          +	else if (xo_flush_h(xop) < 0)
           	    rc = -1;
               }
           
          @@ -5904,6 +6152,53 @@ xo_do_emit (xo_handle_t *xop, const char *fmt)
               return (rc < 0) ? rc : (int) xop->xo_columns;
           }
           
          +/*
          + * Parse and emit a set of fields
          + */
          +static int
          +xo_do_emit (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt)
          +{
          +    xop->xo_columns = 0;	/* Always reset it */
          +    xop->xo_errno = errno;	/* Save for "%m" */
          +
          +    if (fmt == NULL)
          +	return 0;
          +
          +    unsigned max_fields;
          +    xo_field_info_t *fields = NULL;
          +
          +    /* Adjust XOEF_RETAIN based on global flags */
          +    if (XOF_ISSET(xop, XOF_RETAIN_ALL))
          +	flags |= XOEF_RETAIN;
          +    if (XOF_ISSET(xop, XOF_RETAIN_NONE))
          +	flags &= ~XOEF_RETAIN;
          +
          +    /*
          +     * Check for 'retain' flag, telling us to retain the field
          +     * information.  If we've already saved it, then we can avoid
          +     * re-parsing the format string.
          +     */
          +    if (!(flags & XOEF_RETAIN)
          +	|| xo_retain_find(fmt, &fields, &max_fields) != 0
          +	|| fields == NULL) {
          +
          +	/* Nothing retained; parse the format string */
          +	max_fields = xo_count_fields(xop, fmt);
          +	fields = alloca(max_fields * sizeof(fields[0]));
          +	bzero(fields, max_fields * sizeof(fields[0]));
          +
          +	if (xo_parse_fields(xop, fields, max_fields, fmt))
          +	    return -1;		/* Warning already displayed */
          +
          +	if (flags & XOEF_RETAIN) {
          +	    /* Retain the info */
          +	    xo_retain_add(fmt, fields, max_fields);
          +	}
          +    }
          +
          +    return xo_do_emit_fields(xop, fields, max_fields, fmt);
          +}
          +
           /*
            * Rebuild a format string in a gettext-friendly format.  This function
            * is exposed to tools can perform this function.  See xo(1).
          @@ -5944,7 +6239,7 @@ xo_emit_hv (xo_handle_t *xop, const char *fmt, va_list vap)
           
               xop = xo_default(xop);
               va_copy(xop->xo_vap, vap);
          -    rc = xo_do_emit(xop, fmt);
          +    rc = xo_do_emit(xop, 0, fmt);
               va_end(xop->xo_vap);
               bzero(&xop->xo_vap, sizeof(xop->xo_vap));
           
          @@ -5958,7 +6253,7 @@ xo_emit_h (xo_handle_t *xop, const char *fmt, ...)
           
               xop = xo_default(xop);
               va_start(xop->xo_vap, fmt);
          -    rc = xo_do_emit(xop, fmt);
          +    rc = xo_do_emit(xop, 0, fmt);
               va_end(xop->xo_vap);
               bzero(&xop->xo_vap, sizeof(xop->xo_vap));
           
          @@ -5972,13 +6267,137 @@ xo_emit (const char *fmt, ...)
               int rc;
           
               va_start(xop->xo_vap, fmt);
          -    rc = xo_do_emit(xop, fmt);
          +    rc = xo_do_emit(xop, 0, fmt);
               va_end(xop->xo_vap);
               bzero(&xop->xo_vap, sizeof(xop->xo_vap));
           
               return rc;
           }
           
          +int
          +xo_emit_hvf (xo_handle_t *xop, xo_emit_flags_t flags,
          +	     const char *fmt, va_list vap)
          +{
          +    int rc;
          +
          +    xop = xo_default(xop);
          +    va_copy(xop->xo_vap, vap);
          +    rc = xo_do_emit(xop, flags, fmt);
          +    va_end(xop->xo_vap);
          +    bzero(&xop->xo_vap, sizeof(xop->xo_vap));
          +
          +    return rc;
          +}
          +
          +int
          +xo_emit_hf (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...)
          +{
          +    int rc;
          +
          +    xop = xo_default(xop);
          +    va_start(xop->xo_vap, fmt);
          +    rc = xo_do_emit(xop, flags, fmt);
          +    va_end(xop->xo_vap);
          +    bzero(&xop->xo_vap, sizeof(xop->xo_vap));
          +
          +    return rc;
          +}
          +
          +int
          +xo_emit_f (xo_emit_flags_t flags, const char *fmt, ...)
          +{
          +    xo_handle_t *xop = xo_default(NULL);
          +    int rc;
          +
          +    va_start(xop->xo_vap, fmt);
          +    rc = xo_do_emit(xop, flags, fmt);
          +    va_end(xop->xo_vap);
          +    bzero(&xop->xo_vap, sizeof(xop->xo_vap));
          +
          +    return rc;
          +}
          +
          +/*
          + * Emit a single field by providing the info information typically provided
          + * inside the field description (role, modifiers, and formats).  This is
          + * a convenience function to avoid callers using snprintf to build field
          + * descriptions.
          + */
          +int
          +xo_emit_field_hv (xo_handle_t *xop, const char *rolmod, const char *contents,
          +		  const char *fmt, const char *efmt,
          +		  va_list vap)
          +{
          +    int rc;
          +
          +    xop = xo_default(xop);
          +
          +    if (rolmod == NULL)
          +	rolmod = "V";
          +
          +    xo_field_info_t xfi;
          +
          +    bzero(&xfi, sizeof(xfi));
          +
          +    const char *cp;
          +    cp = xo_parse_roles(xop, rolmod, rolmod, &xfi);
          +    if (cp == NULL)
          +	return -1;
          +
          +    xfi.xfi_start = fmt;
          +    xfi.xfi_content = contents;
          +    xfi.xfi_format = fmt;
          +    xfi.xfi_encoding = efmt;
          +    xfi.xfi_clen = contents ? strlen(contents) : 0;
          +    xfi.xfi_flen = fmt ? strlen(fmt) : 0;
          +    xfi.xfi_elen = efmt ? strlen(efmt) : 0;
          +
          +    /* If we have content, then we have a default format */
          +    if (contents && fmt == NULL
          +		&& xo_role_wants_default_format(xfi.xfi_ftype)) {
          +	xfi.xfi_format = xo_default_format;
          +	xfi.xfi_flen = 2;
          +    }
          +
          +
          +
          +    va_copy(xop->xo_vap, vap);
          +
          +    rc = xo_do_emit_fields(xop, &xfi, 1, fmt ?: contents ?: "field");
          +
          +    va_end(xop->xo_vap);
          +
          +    return rc;
          +}
          +
          +int
          +xo_emit_field_h (xo_handle_t *xop, const char *rolmod, const char *contents,
          +		 const char *fmt, const char *efmt, ...)
          +{
          +    int rc;
          +    va_list vap;
          +
          +    va_start(vap, efmt);
          +    rc = xo_emit_field_hv(xop, rolmod, contents, fmt, efmt, vap);
          +    va_end(vap);
          +
          +    return rc;
          +}
          +
          +int
          +xo_emit_field (const char *rolmod, const char *contents,
          +	       const char *fmt, const char *efmt, ...)
          +{
          +    int rc;
          +    va_list vap;
          +
          +    va_start(vap, efmt);
          +    rc = xo_emit_field_hv(NULL, rolmod, contents, fmt, efmt, vap);
          +    va_end(vap);
          +
          +    return rc;
          +}
          +
           int
           xo_attr_hv (xo_handle_t *xop, const char *name, const char *fmt, va_list vap)
           {
          @@ -6392,7 +6811,7 @@ xo_open_list_hf (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name)
           }
           
           int
          -xo_open_list_h (xo_handle_t *xop, const char *name UNUSED)
          +xo_open_list_h (xo_handle_t *xop, const char *name)
           {
               return xo_open_list_hf(xop, 0, name);
           }
          @@ -6404,7 +6823,7 @@ xo_open_list (const char *name)
           }
           
           int
          -xo_open_list_hd (xo_handle_t *xop, const char *name UNUSED)
          +xo_open_list_hd (xo_handle_t *xop, const char *name)
           {
               return xo_open_list_hf(xop, XOF_DTRT, name);
           }
          @@ -7113,6 +7532,11 @@ xo_transition (xo_handle_t *xop, xo_xsf_flags_t flags, const char *name,
           		   xsp->xs_state, new_state);
               }
           
          +    /* Handle the flush flag */
          +    if (rc >= 0 && XOF_ISSET(xop, XOF_FLUSH))
          +	if (xo_flush_h(xop))
          +	    rc = -1;
          +
               return rc;
           
            marker_prevents_close:
          @@ -7179,22 +7603,11 @@ xo_set_allocator (xo_realloc_func_t realloc_func, xo_free_func_t free_func)
           int
           xo_flush_h (xo_handle_t *xop)
           {
          -    static char div_close[] = "";
               int rc;
           
               xop = xo_default(xop);
           
               switch (xo_style(xop)) {
          -    case XO_STYLE_HTML:
          -	if (XOIF_ISSET(xop, XOIF_DIV_OPEN)) {
          -	    XOIF_CLEAR(xop, XOIF_DIV_OPEN);
          -	    xo_data_append(xop, div_close, sizeof(div_close) - 1);
          -
          -	    if (XOF_ISSET(xop, XOF_PRETTY))
          -		xo_data_append(xop, "\n", 1);
          -	}
          -	break;
          -
               case XO_STYLE_ENCODER:
           	xo_encoder_handle(xop, XO_OP_FLUSH, NULL, NULL);
               }
          @@ -7435,7 +7848,7 @@ xo_set_program (const char *name)
           }
           
           void
          -xo_set_version_h (xo_handle_t *xop, const char *version UNUSED)
          +xo_set_version_h (xo_handle_t *xop, const char *version)
           {
               xop = xo_default(xop);
           
          diff --git a/libxo/xo.h b/libxo/xo.h
          index 88bcce2999df..310b21cae366 100644
          --- a/libxo/xo.h
          +++ b/libxo/xo.h
          @@ -94,6 +94,11 @@ typedef unsigned long long xo_xof_flags_t;
           
           #define XOF_LOG_GETTEXT	XOF_BIT(28) /** Log (stderr) gettext lookup strings */
           #define XOF_UTF8	XOF_BIT(29) /** Force text output to be UTF8 */
          +#define XOF_RETAIN_ALL	XOF_BIT(30) /** Force use of XOEF_RETAIN */
          +#define XOF_RETAIN_NONE	XOF_BIT(31) /** Prevent use of XOEF_RETAIN */
          +
          +typedef unsigned xo_emit_flags_t; /* Flags to xo_emit() and friends */
          +#define XOEF_RETAIN	(1<<0)	  /* Retain parsed formatting information */
           
           /*
            * The xo_info_t structure provides a mapping between names and
          @@ -162,6 +167,12 @@ xo_set_flags (xo_handle_t *xop, xo_xof_flags_t flags);
           void
           xo_clear_flags (xo_handle_t *xop, xo_xof_flags_t flags);
           
          +int
          +xo_set_file_h (xo_handle_t *xop, FILE *fp);
          +
          +int
          +xo_set_file (FILE *fp);
          +
           void
           xo_set_info (xo_handle_t *xop, xo_info_t *infop, int count);
           
          @@ -180,6 +191,16 @@ xo_emit_h (xo_handle_t *xop, const char *fmt, ...);
           int
           xo_emit (const char *fmt, ...);
           
          +int
          +xo_emit_hvf (xo_handle_t *xop, xo_emit_flags_t flags,
          +	     const char *fmt, va_list vap);
          +
          +int
          +xo_emit_hf (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...);
          +
          +int
          +xo_emit_f (xo_emit_flags_t flags, const char *fmt, ...);
          +
           PRINTFLIKE(2, 0)
           static inline int
           xo_emit_hvp (xo_handle_t *xop, const char *fmt, va_list vap)
          @@ -209,6 +230,36 @@ xo_emit_p (const char *fmt, ...)
               return rc;
           }
           
          +PRINTFLIKE(3, 0)
          +static inline int
          +xo_emit_hvfp (xo_handle_t *xop, xo_emit_flags_t flags,
          +	      const char *fmt, va_list vap)
          +{
          +    return xo_emit_hvf(xop, flags, fmt, vap);
          +}
          +
          +PRINTFLIKE(3, 4)
          +static inline int
          +xo_emit_hfp (xo_handle_t *xop, xo_emit_flags_t flags, const char *fmt, ...)
          +{
          +    va_list vap;
          +    va_start(vap, fmt);
          +    int rc = xo_emit_hvf(xop, flags, fmt, vap);
          +    va_end(vap);
          +    return rc;
          +}
          +
          +PRINTFLIKE(2, 3)
          +static inline int
          +xo_emit_fp (xo_emit_flags_t flags, const char *fmt, ...)
          +{
          +    va_list vap;
          +    va_start(vap, fmt);
          +    int rc = xo_emit_hvf(NULL, flags, fmt, vap);
          +    va_end(vap);
          +    return rc;
          +}
          +
           int
           xo_open_container_h (xo_handle_t *xop, const char *name);
           
          @@ -593,4 +644,23 @@ char *
           xo_simplify_format (xo_handle_t *xop, const char *fmt, int with_numbers,
           		    xo_simplify_field_func_t field_cb);
           
          +int
          +xo_emit_field_hv (xo_handle_t *xop, const char *rolmod, const char *contents,
          +		  const char *fmt, const char *efmt,
          +		  va_list vap);
          +
          +int
          +xo_emit_field_h (xo_handle_t *xop, const char *rolmod, const char *contents,
          +		 const char *fmt, const char *efmt, ...);
          +
          +int
          +xo_emit_field (const char *rolmod, const char *contents,
          +	       const char *fmt, const char *efmt, ...);
          +
          +void
          +xo_retain_clear_all (void);
          +
          +void
          +xo_retain_clear (const char *fmt);
          +
           #endif /* INCLUDE_XO_H */
          diff --git a/libxo/xo_emit_f.3 b/libxo/xo_emit_f.3
          new file mode 100644
          index 000000000000..087954631516
          --- /dev/null
          +++ b/libxo/xo_emit_f.3
          @@ -0,0 +1,111 @@
          +.\" #
          +.\" # Copyright (c) 2016, Juniper Networks, Inc.
          +.\" # All rights reserved.
          +.\" # This SOFTWARE is licensed under the LICENSE provided in the
          +.\" # ../Copyright file. By downloading, installing, copying, or 
          +.\" # using the SOFTWARE, you agree to be bound by the terms of that
          +.\" # LICENSE.
          +.\" # Phil Shafer, April 2016
          +.\" 
          +.Dd April 15, 2016
          +.Dt LIBXO 3
          +.Os
          +.Sh NAME
          +.Nm xo_emit_f , xo_emit_hf , xo_emit_hvf
          +.Nd emit formatted output based on format string and arguments
          +.Sh LIBRARY
          +.Lb libxo
          +.Sh SYNOPSIS
          +.In libxo/xo.h
          +.Ft int
          +.Fn xo_emit_f "xo_emit_flags_t flags" "const char *fmt"  "..."
          +.Ft int
          +.Fn xo_emit_hf "xo_handle_t *xop" "xo_emit_flags_t flags" "const char *fmt" "..."
          +.Ft int
          +.Fn xo_emit_hvf "xo_handle_t *xop" "xo_emit_flags_t flags" "const char *fmt" "va_list vap"
          +.Ft void
          +.Fn xo_retain_clear_all "void"
          +.Ft void
          +.Fn xo_retain_clear "const char *fmt"
          +.Sh DESCRIPTION
          +These functions allow callers to pass a set of flags to
          +.Nm
          +emitting functions.  These processing of arguments, except for
          +.Fa flags ,
          +is identical to the base functions.
          +See
          +.Xr xo_emit 3
          +for additional information.
          +.Pp
          +The only currently defined flag is
          +.Dv XOEF_RETAIN .
          +.Nm
          +can retain the parsed internal information related to the given
          +format string, allowing subsequent
          +.Xr xo_emit 3
          +calls, the retained
          +information is used, avoiding repetitive parsing of the format string.
          +To retain parsed format information, use the
          +.Dv XOEF_RETAIN
          +flag to the
          +.Fn xo_emit_f
          +function.
          +.Pp
          +The format string must be immutable across multiple calls to
          +.Xn xo_emit_f ,
          +since the library retains the string.
          +Typically this is done by using
          +static constant strings, such as string literals. If the string is not
          +immutable, the
          +.Dv XOEF_RETAIN
          +flag must not be used.
          +.Pp
          +The functions
          +.Fn xo_retain_clear
          +and
          +.Fn xo_retain_clear_all
          +release internal information on either a single format string or all
          +format strings, respectively.
          +Neither is required, but the library will
          +retain this information until it is cleared or the process exits.
          +.Pp
          +The retained information is kept as thread-specific data.
          +.Pp
          +Use
          +.Fn xo_retain_clear
          +and
          +.Fn xo_retain_clear_all
          +to clear the retained information, clearing the retained information
          +for either a specific format string or all format strings, respectively.
          +These functions are only needed when the calling application wants to
          +clear this information; they are not generally needed.
          +.Sh EXAMPLES
          +.Pp
          +.Bd  -literal -offset indent
          +    for (i = 0; i < 1000; i++) {
          +        xo_open_instance("item");
          +        xo_emit_f(XOEF_RETAIN, "{:name}  {:count/%d}\n",
          +                  name[i], count[i]);
          +    }
          +.Ed
          +.Pp
          +In this example, the caller desires to clear the retained information.
          +.Bd  -literal -offset indent
          +    const char *fmt = "{:name}  {:count/%d}\n";
          +    for (i = 0; i < 1000; i++) {
          +        xo_open_instance("item");
          +        xo_emit_f(XOEF_RETAIN, fmt, name[i], count[i]);
          +    }
          +    xo_retain_clear(fmt);
          +.Ed
          +.Sh RETURN CODE
          +The return values for these functions is identical to those of their
          +traditional counterparts.  See
          +.Xr xo_emit 3
          +for details.
          +.Sh SEE ALSO
          +.Xr xo_emit 3 ,
          +.Xr xo_open_container 3 ,
          +.Xr xo_open_list 3 ,
          +.Xr xo_format 5 ,
          +.Xr libxo 3
          diff --git a/libxo/xo_format.5 b/libxo/xo_format.5
          index 8c3cbea31248..d0e6a33abbda 100644
          --- a/libxo/xo_format.5
          +++ b/libxo/xo_format.5
          @@ -51,14 +51,14 @@ field descriptions within the format string.
           .Pp
           The field description is given as follows:
           .Bd -literal -offset indent
          -    '{' [ role | modifier ]* [',' long-names ]* ':' [ content ]
          -            [ '/' field-format [ '/' encoding-format ]] '}'
          +    \(aq{\(aq [ role | modifier ]* [\(aq,\(aq long\-names ]* \(aq:\(aq [ content ]
          +            [ \(aq/\(aq field\-format [ \(aq/\(aq encoding\-format ]] \(aq}\(aq
           .Ed
           .Pp
           The role describes the function of the field, while the modifiers
           enable optional behaviors.
          -The contents, field-format, and
          -encoding-format are used in varying ways, based on the role.
          +The contents, field\-format, and
          +encoding\-format are used in varying ways, based on the role.
           These are described in the following sections.
           .Pp
           Braces can be escaped by using double braces, similar to "%%" in
          @@ -68,26 +68,26 @@ The format string "{{braces}}" would emit "{braces}".
           In the following example, three field descriptors appear.
           The first
           is a padding field containing three spaces of padding, the second is a
          -label ("In stock"), and the third is a value field ("in-stock").
          -The in-stock field has a "%u" format that will parse the next argument
          +label ("In stock"), and the third is a value field ("in\-stock").
          +The in\-stock field has a "%u" format that will parse the next argument
           passed to the
           .Xr xo_emit 3 ,
           function as an unsigned integer.
           .Bd -literal -offset indent
          -    xo_emit("{P:   }{Lwc:In stock}{:in-stock/%u}\\n", 65);
          +    xo_emit("{P:   }{Lwc:In stock}{:in\-stock/%u}\\n", 65);
           .Ed
           .Pp
           This single line of code can generate text ("In stock: 65\\n"), XML
          -("65"), JSON ('"in-stock": 65'), or HTML (too
          +("65"), JSON (\(aq"in\-stock": 65\(aq), or HTML (too
           lengthy to be listed here).
           .Pp
           While roles and modifiers typically use single character for brevity,
           there are alternative names for each which allow more verbose
           formatting strings.
           These names must be preceded by a comma, and may follow any
          -single-character values:
          +single\-character values:
           .Bd -literal -offset indent
          -    xo_emit("{L,white,colon:In stock}{,key:in-stock/%u}\n", 65);
          +    xo_emit("{L,white,colon:In stock}{,key:in\-stock/%u}\\n", 65);
           .Ed
           .Ss "Field Roles"
           Field roles are optional, and indicate the role and formatting of the
          @@ -96,7 +96,7 @@ The roles are listed below; only one role is permitted:
           .Bl -column "M" "Name12341234"
           .It Sy "M" "Name        " "Description"
           .It C "color       " "Field is a color or effect"
          -.It D "decoration  " "Field is non-text (e.g. colon, comma)"
          +.It D "decoration  " "Field is non\-text (e.g. colon, comma)"
           .It E "error       " "Field is an error message"
           .It L "label       " "Field is text that prefixes a value"
           .It N "note        " "Field is text that follows a value"
          @@ -105,12 +105,12 @@ The roles are listed below; only one role is permitted:
           .It U "units       " "Field is the units for the previous value field"
           .It V "value       " "Field is the name of field (the default)"
           .It W "warning     " "Field is a warning message"
          -.It \&[ "start-anchor" "Begin a section of anchored variable-width text"
          -.It \&] "stop-anchor " "End a section of anchored variable-width text"
          +.It \&[ "start\-anchor" "Begin a section of anchored variable\-width text"
          +.It \&] "stop\-anchor " "End a section of anchored variable\-width text"
           .El
           .Bd -literal -offset indent
              EXAMPLE:
          -       xo_emit("{L:Free}{D::}{P:   }{:free/%u} {U:Blocks}\n",
          +       xo_emit("{L:Free}{D::}{P:   }{:free/%u} {U:Blocks}\\n",
                          free_blocks);
           .Ed
           .Pp
          @@ -121,50 +121,50 @@ a comma:
           .Bd -literal -offset indent
              EXAMPLE:
                   xo_emit("{,label:Free}{,decoration::}{,padding:   }"
          -               "{,value:free/%u} {,units:Blocks}\n",
          +               "{,value:free/%u} {,units:Blocks}\\n",
                          free_blocks);
           .Ed
           .Ss "The Color Role ({C:})"
           Colors and effects control how text values are displayed; they are
           used for display styles (TEXT and HTML).
           .Bd -literal -offset indent
          -    xo_emit("{C:bold}{:value}{C:no-bold}\n", value);
          +    xo_emit("{C:bold}{:value}{C:no\-bold}\\n", value);
           .Ed
           .Pp
          -Colors and effects remain in effect until modified by other "C"-role
          +Colors and effects remain in effect until modified by other "C"\-role
           fields.
           .Bd -literal -offset indent
          -    xo_emit("{C:bold}{C:inverse}both{C:no-bold}only inverse\n");
          +    xo_emit("{C:bold}{C:inverse}both{C:no\-bold}only inverse\\n");
           .Ed
           .Pp
           If the content is empty, the "reset" action is performed.
           .Bd -literal -offset indent
          -    xo_emit("{C:both,underline}{:value}{C:}\n", value);
          +    xo_emit("{C:both,underline}{:value}{C:}\\n", value);
           .Ed
           .Pp
          -The content should be a comma-separated list of zero or more colors or
          +The content should be a comma\-separated list of zero or more colors or
           display effects.
           .Bd -literal -offset indent
          -    xo_emit("{C:bold,underline,inverse}All three{C:no-bold,no-inverse}\n");
          +    xo_emit("{C:bold,underline,inverse}All three{C:no\-bold,no\-inverse}\\n");
           .Ed
           .Pp
           The color content can be either static, when placed directly within
          -the field descriptor, or a printf-style format descriptor can be used,
          +the field descriptor, or a printf\-style format descriptor can be used,
           if preceded by a slash ("/"):
           .Bd -literal -offset indent
              xo_emit("{C:/%s%s}{:value}{C:}", need_bold ? "bold" : "",
                      need_underline ? "underline" : "", value);
           .Ed
           .Pp
          -Color names are prefixed with either "fg-" or "bg-" to change the
          +Color names are prefixed with either "fg\-" or "bg\-" to change the
           foreground and background colors, respectively.
           .Bd -literal -offset indent
          -    xo_emit("{C:/fg-%s,bg-%s}{Lwc:Cost}{:cost/%u}{C:reset}\n",
          +    xo_emit("{C:/fg\-%s,bg\-%s}{Lwc:Cost}{:cost/%u}{C:reset}\\n",
                       fg_color, bg_color, cost);
           .Ed
           .Pp
           The following table lists the supported effects:
          -.Bl -column "no-underline"
          +.Bl -column "no\-underline"
           .It Sy "Name         " "Description"
           .It "bg\-xxxxx     " "Change background color"
           .It "bold         " "Start bold text effect"
          @@ -179,7 +179,7 @@ The following table lists the supported effects:
           .El
           .Pp
           The following color names are supported:
          -.Bl -column "no-underline"
          +.Bl -column "no\-underline"
           .It Sy "Name"
           .It black
           .It blue
          @@ -193,7 +193,7 @@ The following color names are supported:
           .El
           .Ss "The Decoration Role ({D:})"
           Decorations are typically punctuation marks such as colons,
          -semi-colons, and commas used to decorate the text and make it simpler
          +semi\-colons, and commas used to decorate the text and make it simpler
           for human readers.
           By marking these distinctly, HTML usage scenarios
           can use CSS to direct their display parameters.
          @@ -219,22 +219,23 @@ change such as changing "/%06d" to "/%08d" should not force hand
           inspection of all .po files.
           .Pp
           The simplified version can be generated for a single message using the
          -"xopo -s " command, or an entire .pot can be translated using
          -the "xopo -f  -o " command.
          +"xopo \-s " command, or an entire .pot can be translated using
          +the "xopo \-f  \-o " command.
           .Bd -literal -offset indent
          -   xo_emit("{G:}Invalid token\n");
          +   xo_emit("{G:}Invalid token\\n");
           .Ed
          +.Pp
           The {G:} role allows a domain name to be set.
           .Fn gettext
           calls will
           continue to use that domain name until the current format string
           processing is complete, enabling a library function to emit strings
          -using it's own catalog.
          +using it\(aqs own catalog.
           The domain name can be either static as the
           content of the field, or a format can be used to get the domain name
           from the arguments.
           .Bd -literal -offset indent
          -   xo_emit("{G:libc}Service unavailable in restricted mode\n");
          +   xo_emit("{G:libc}Service unavailable in restricted mode\\n");
           .Ed
           .Ss "The Label Role ({L:})"
           Labels are text that appears before a value.
          @@ -249,7 +250,7 @@ Notes are text that appears after a value.
           .Ss "The Padding Role ({P:})"
           Padding represents whitespace used before and between fields.
           The padding content can be either static, when placed directly within
          -the field descriptor, or a printf-style format descriptor can be used,
          +the field descriptor, or a printf\-style format descriptor can be used,
           if preceded by a slash ("/"):
           .Bd -literal -offset indent
               xo_emit("{P:        }{Lwc:Cost}{:cost/%u}\\n", cost);
          @@ -259,7 +260,7 @@ if preceded by a slash ("/"):
           Titles are heading or column headers that are meant to be displayed to
           the user.
           The title can be either static, when placed directly within
          -the field descriptor, or a printf-style format descriptor can be used,
          +the field descriptor, or a printf\-style format descriptor can be used,
           if preceded by a slash ("/"):
           .Bd -literal -offset indent
               xo_emit("{T:Interface Statistics}\\n");
          @@ -274,7 +275,7 @@ for the previous value field.
               xo_emit("{Lwc:Distance}{:distance/%u}{Uw:miles}\\n", miles);
           .Ed
           .Pp
          -Note that the sense of the 'w' modifier is reversed for units;
          +Note that the sense of the \(aqw\(aq modifier is reversed for units;
           a blank is added before the contents, rather than after it.
           .Pp
           When the
          @@ -286,14 +287,14 @@ attribute:
               50
           .Ed
           .Pp
          -Units can also be rendered in HTML as the "data-units" attribute:
          +Units can also be rendered in HTML as the "data\-units" attribute:
           .Bd -literal -offset indent
          -    
          50
          +
          50
          .Ed .Ss "The Value Role ({V:} and {:})" The value role is used to represent the a data value that is -interesting for the non-display output styles (XML and JSON). +interesting for the non\-display output styles (XML and JSON). Value is the default role; if no other role designation is given, the field is a value. @@ -356,16 +357,17 @@ Field modifiers are flags which modify the way content emitted for particular output styles: .Bl -column M "Name123456789" .It Sy M "Name " "Description" +.It a "argument " "The content appears as a ""const char *"" argument" .It c "colon " "A colon ("":"") is appended after the label" .It d "display " "Only emit field for display styles (text/HTML)" .It e "encoding " "Only emit for encoding styles (XML/JSON)" -.It h "humanize (hn) " "Format large numbers in human-readable style" -.It " " "hn-space " "Humanize: Place space between numeric and unit" -.It " " "hn-decimal " "Humanize: Add a decimal digit, if number < 10" -.It " " "hn-1000 " "Humanize: Use 1000 as divisor instead of 1024" +.It h "humanize (hn) " "Format large numbers in human\-readable style" +.It " " "hn\-space " "Humanize: Place space between numeric and unit" +.It " " "hn\-decimal " "Humanize: Add a decimal digit, if number < 10" +.It " " "hn\-1000 " "Humanize: Use 1000 as divisor instead of 1024" .It k "key " "Field is a key, suitable for XPath predicates" -.It l "leaf-list " "Field is a leaf-list, a list of leaf values" -.It n "no-quotes " "Do not quote the field when using JSON style" +.It l "leaf\-list " "Field is a leaf\-list, a list of leaf values" +.It n "no\-quotes " "Do not quote the field when using JSON style" .It q "quotes " "Quote the field when using JSON style" .It t "trim " "Trim leading and trailing whitespace" .It w "white space " "A blank ("" "") is appended after the label" @@ -373,7 +375,7 @@ particular output styles: .Pp For example, the modifier string "Lwc" means the field has a label role (text that describes the next field) and should be followed by a -colon ('c') and a space ('w'). +colon (\(aqc\(aq) and a space (\(aqw\(aq). The modifier string "Vkq" means the field has a value role, that it is a key for the current instance, and that the value should be quoted when encoded for JSON. @@ -382,10 +384,31 @@ Roles and modifiers can also use more verbose names, when preceeded by a comma. For example, the modifier string "Lwc" (or "L,white,colon") means the field has a label role (text that describes the next field) -and should be followed by a colon ('c') and a space ('w'). +and should be followed by a colon (\(aqc\(aq) and a space (\(aqw\(aq). The modifier string "Vkq" (or ":key,quote") means the field has a value role (the default role), that it is a key for the current instance, and that the value should be quoted when encoded for JSON. +.Ss "The Argument Modifier ({a:})" +The argument modifier indicates that the content of the field +descriptor will be placed as a UTF\-8 string (const char *) argument +within the xo_emit parameters. +.Bd -literal -offset indent + EXAMPLE: + xo_emit("{La:} {a:}\\n", "Label text", "label", "value"); + TEXT: + Label text value + JSON: + "label": "value" + XML: + +.Ed +.Pp +The argument modifier allows field names for value fields to be passed +on the stack, avoiding the need to build a field descriptor using +.Xr snprintf 1 . +For many field roles, the argument modifier is not needed, +since those roles have specific mechanisms for arguments, +such as "{C:fg\-%s}". .Ss "The Colon Modifier ({c:})" The colon modifier appends a single colon to the data value: .Bd -literal -offset indent @@ -397,7 +420,7 @@ The colon modifier appends a single colon to the data value: .Pp The colon modifier is only used for the TEXT and HTML output styles. -It is commonly combined with the space modifier ('{w:}'). +It is commonly combined with the space modifier (\(aq{w:}\(aq). It is purely a convenience feature. .Ss "The Display Modifier ({d:})" The display modifier indicated the field should only be generated for @@ -429,39 +452,39 @@ The encoding modifier is the opposite of the display modifier, and they are often used to give to distinct views of the underlying data. .Ss "The Humanize Modifier ({h:})" The humanize modifier is used to render large numbers as in a -human-readable format. +human\-readable format. While numbers like "44470272" are completely readable to computers and savants, humans will generally find "44M" more meaningful. .Pp "hn" can be used as an alias for "humanize". .Pp The humanize modifier only affects display styles (TEXT and HMTL). -The "no-humanize" option will block the function of the humanize modifier. +The "no\-humanize" option will block the function of the humanize modifier. .Pp There are a number of modifiers that affect details of humanization. These are only available in as full names, not single characters. -The "hn-space" modifier places a space between the number and any +The "hn\-space" modifier places a space between the number and any multiplier symbol, such as "M" or "K" (ex: "44 K"). -The "hn-decimal" modifier will add a decimal point and a single tenths digit +The "hn\-decimal" modifier will add a decimal point and a single tenths digit when the number is less than 10 (ex: "4.4K"). -The "hn-1000" modifier will use 1000 as divisor instead of 1024, following the -JEDEC-standard instead of the more natural binary powers-of-two +The "hn\-1000" modifier will use 1000 as divisor instead of 1024, following the +JEDEC\-standard instead of the more natural binary powers\-of\-two tradition. .Bd -literal -offset indent EXAMPLE: - xo_emit("{h:input/%u}, {h,hn-space:output/%u}, " - "{h,hn-decimal:errors/%u}, {h,hn-1000:capacity/%u}, " - "{h,hn-decimal:remaining/%u}\n", + xo_emit("{h:input/%u}, {h,hn\-space:output/%u}, " + "{h,hn\-decimal:errors/%u}, {h,hn\-1000:capacity/%u}, " + "{h,hn\-decimal:remaining/%u}\\n", input, output, errors, capacity, remaining); TEXT: 21, 57 K, 96M, 44M, 1.2G .Ed .Pp In the HTML style, the original numeric value is rendered in the -"data-number" attribute on the
          element: +"data\-number" attribute on the
          element: .Bd -literal -offset indent -
          96M
          +
          96M
          .Ed .Ss "The Gettext Modifier ({g:})" The gettext modifier is used to translate individual fields using the @@ -476,9 +499,9 @@ translation. In the following example, the strings "State" and "full" are passed to .Fn gettext -to find locale-based translated strings. +to find locale\-based translated strings. .Bd -literal -offset indent - xo_emit("{Lgwc:State}{g:state}\n", "full"); + xo_emit("{Lgwc:State}{g:state}\\n", "full"); .Ed .Ss "The Key Modifier ({k:})" The key modifier is used to indicate that a particular field helps @@ -499,15 +522,15 @@ Currently the key modifier is only used when generating XPath values for the HTML output style when .Dv XOF_XPATH is set, but other uses are likely in the near future. -.Ss "The Leaf-List Modifier ({l:})" -The leaf-list modifier is used to distinguish lists where each +.Ss "The Leaf\-List Modifier ({l:})" +The leaf\-list modifier is used to distinguish lists where each instance consists of only a single value. In XML, these are rendered as single elements, where JSON renders them as arrays. .Bd -literal -offset indent EXAMPLE: xo_open_list("user"); for (i = 0; i < num_users; i++) { - xo_emit("Member {l:name}\n", user[i].u_name); + xo_emit("Member {l:name}\\n", user[i].u_name); } xo_close_list("user"); XML: @@ -516,8 +539,8 @@ rendered as single elements, where JSON renders them as arrays. JSON: "user": [ "phil", "pallavi" ] .Ed -.Ss "The No-Quotes Modifier ({n:})" -The no-quotes modifier (and its twin, the 'quotes' modifier) affect +.Ss "The No\-Quotes Modifier ({n:})" +The no\-quotes modifier (and its twin, the \(aqquotes\(aq modifier) affect the quoting of values in the JSON output style. JSON uses quotes for string values, but no quotes for numeric, boolean, and null data. @@ -538,8 +561,9 @@ language settings. The contents of the field should be the singular and plural English values, separated by a comma: .Bd -literal -offset indent - xo_emit("{:bytes} {Ngp:byte,bytes}\n", bytes); + xo_emit("{:bytes} {Ngp:byte,bytes}\\n", bytes); .Ed +.Pp The plural modifier is meant to work with the gettext modifier ({g:}) but can work independently. .Pp @@ -554,7 +578,7 @@ function is called to handle the heavy lifting, using the message catalog to convert the singular and plural forms into the native language. .Ss "The Quotes Modifier ({q:})" -The quotes modifier (and its twin, the 'no-quotes' modifier) affect +The quotes modifier (and its twin, the \(aqno-quotes\(aq modifier) affect the quoting of values in the JSON output style. JSON uses quotes for string values, but no quotes for numeric, boolean, and null data. @@ -578,23 +602,23 @@ The white space modifier appends a single space to the data value: .Pp The white space modifier is only used for the TEXT and HTML output styles. -It is commonly combined with the colon modifier ('{c:}'). +It is commonly combined with the colon modifier (\(aq{c:}\(aq). It is purely a convenience feature. .Pp -Note that the sense of the 'w' modifier is reversed for the units role +Note that the sense of the \(aqw\(aq modifier is reversed for the units role ({Uw:}); a blank is added before the contents, rather than after it. .Ss "Field Formatting" The field format is similar to the format string for .Xr printf 3 . Its use varies based on the role of the field, but generally is used to -format the field's contents. +format the field\(aqs contents. .Pp If the format string is not provided for a value field, it defaults to "%s". .Pp -Note a field definition can contain zero or more printf-style +Note a field definition can contain zero or more printf\-style .Dq directives , -which are sequences that start with a '%' and end with +which are sequences that start with a \(aq%\(aq and end with one of following characters: "diouxXDOUeEfFgGaAcCsSp". Each directive is matched by one of more arguments to the @@ -603,54 +627,54 @@ function. .Pp The format string has the form: .Bd -literal -offset indent - '%' format-modifier * format-character + \(aq%\(aq format\-modifier * format\-character .Ed .Pp -The format- modifier can be: +The format\- modifier can be: .Bl -bullet .It -a '#' character, indicating the output value should be prefixed with +a \(aq#\(aq character, indicating the output value should be prefixed with "0x", typically to indicate a base 16 (hex) value. .It -a minus sign ('-'), indicating the output value should be padded on +a minus sign (\(aq\-\(aq), indicating the output value should be padded on the right instead of the left. .It -a leading zero ('0') indicating the output value should be padded on the -left with zeroes instead of spaces (' '). +a leading zero (\(aq0\(aq) indicating the output value should be padded on the +left with zeroes instead of spaces (\(aq \(aq). .It -one or more digits ('0' - '9') indicating the minimum width of the +one or more digits (\(aq0\(aq \- \(aq9\(aq) indicating the minimum width of the argument. If the width in columns of the output value is less than the minimum width, the value will be padded to reach the minimum. .It a period followed by one or more digits indicating the maximum number of bytes which will be examined for a string argument, or the maximum -width for a non-string argument. +width for a non\-string argument. When handling ASCII strings this -functions as the field width but for multi-byte characters, a single +functions as the field width but for multi\-byte characters, a single character may be composed of multiple bytes. .Xr xo_emit 3 will never dereference memory beyond the given number of bytes. .It a second period followed by one or more digits indicating the maximum width for a string argument. -This modifier cannot be given for non-string arguments. +This modifier cannot be given for non\-string arguments. .It -one or more 'h' characters, indicating shorter input data. +one or more \(aqh\(aq characters, indicating shorter input data. .It -one or more 'l' characters, indicating longer input data. +one or more \(aql\(aq characters, indicating longer input data. .It -a 'z' character, indicating a 'size_t' argument. +a \(aqz\(aq character, indicating a \(aqsize_t\(aq argument. .It -a 't' character, indicating a 'ptrdiff_t' argument. +a \(aqt\(aq character, indicating a \(aqptrdiff_t\(aq argument. .It -a ' ' character, indicating a space should be emitted before +a \(aq \(aq character, indicating a space should be emitted before positive numbers. .It -a '+' character, indicating sign should emitted before any number. +a \(aq+\(aq character, indicating sign should emitted before any number. .El .Pp -Note that 'q', 'D', 'O', and 'U' are considered deprecated and will be +Note that \(aqq\(aq, \(aqD\(aq, \(aqO\(aq, and \(aqU\(aq are considered deprecated and will be removed eventually. .Pp The format character is described in the following table: @@ -665,22 +689,22 @@ The format character is described in the following table: .It D "long " "base 10 (decimal)" .It O "unsigned long " "base 8 (octal)" .It U "unsigned long " "base 10 (decimal)" -.It e "double " "[-]d.ddde+-dd" -.It E "double " "[-]d.dddE+-dd" -.It f "double " "[-]ddd.ddd" -.It F "double " "[-]ddd.ddd" -.It g "double " "as 'e' or 'f'" -.It G "double " "as 'E' or 'F'" -.It a "double " "[-]0xh.hhhp[+-]d" -.It A "double " "[-]0Xh.hhhp[+-]d" +.It e "double " "[\-]d.ddde+\-dd" +.It E "double " "[\-]d.dddE+\-dd" +.It f "double " "[\-]ddd.ddd" +.It F "double " "[\-]ddd.ddd" +.It g "double " "as \(aqe\(aq or \(aqf\(aq" +.It G "double " "as \(aqE\(aq or \(aqF\(aq" +.It a "double " "[\-]0xh.hhhp[+\-]d" +.It A "double " "[\-]0Xh.hhhp[+\-]d" .It c "unsigned char " "a character" .It C "wint_t " "a character" -.It s "char * " "a UTF-8 string" +.It s "char * " "a UTF\-8 string" .It S "wchar_t * " "a unicode/WCS string" -.It p "void * " "'%#lx'" +.It p "void * " "\(aq%#lx\(aq" .El .Pp -The 'h' and 'l' modifiers affect the size and treatment of the +The \(aqh\(aq and \(aql\(aq modifiers affect the size and treatment of the argument: .Bl -column "Mod" "d, i " "o, u, x, X " .It Sy "Mod" "d, i " "o, u, x, X" @@ -693,27 +717,27 @@ argument: .It "z " "size_t " "size_t" .It "q " "quad_t " "u_quad_t" .El -.Ss "UTF-8 and Locale Strings" +.Ss "UTF\-8 and Locale Strings" All strings for .Nm libxo -must be UTF-8. +must be UTF\-8. .Nm libxo will handle turning them -into locale-based strings for display to the user. +into locale\-based strings for display to the user. .Pp -For strings, the 'h' and 'l' modifiers affect the interpretation of +For strings, the \(aqh\(aq and \(aql\(aq modifiers affect the interpretation of the bytes pointed to argument. -The default '%s' string is a 'char *' -pointer to a string encoded as UTF-8. -Since UTF-8 is compatible with +The default \(aq%s\(aq string is a \(aqchar *\(aq +pointer to a string encoded as UTF\-8. +Since UTF\-8 is compatible with .Em ASCII -data, a normal 7-bit +data, a normal 7\-bit .Em ASCII string can be used. "%ls" expects a -"wchar_t *" pointer to a wide-character string, encoded as 32-bit +"wchar_t *" pointer to a wide\-character string, encoded as 32\-bit Unicode values. -"%hs" expects a "char *" pointer to a multi-byte +"%hs" expects a "char *" pointer to a multi\-byte string encoded with the current locale, as given by the .Ev LC_CTYPE , .Ev LANG , @@ -722,22 +746,22 @@ or environment variables. The first of this list of variables is used and if none of the variables are set, the locale defaults to -.Em UTF-8 . +.Em UTF\-8 . .Pp .Nm libxo will -convert these arguments as needed to either UTF-8 (for XML, JSON, and -HTML styles) or locale-based strings for display in text style. +convert these arguments as needed to either UTF\-8 (for XML, JSON, and +HTML styles) or locale\-based strings for display in text style. .Bd -literal -offset indent - xo_emit("All strings are utf-8 content {:tag/%ls}", + xo_emit("All strings are utf\-8 content {:tag/%ls}", L"except for wide strings"); .Ed .Pp "%S" is equivalent to "%ls". .Pp -For example, a function is passed a locale-base name, a hat size, +For example, a function is passed a locale\-base name, a hat size, and a time value. -The hat size is formatted in a UTF-8 (ASCII) +The hat size is formatted in a UTF\-8 (ASCII) string, and the time value is formatted into a wchar_t string. .Bd -literal -offset indent void print_order (const char *name, int size, @@ -755,7 +779,7 @@ string, and the time value is formatted into a wchar_t string. xo_emit("The hat for {:name/%hs} is {:size/%s}.\\n", name, size_val); - xo_emit("It was ordered on {:order-time/%ls}.\\n", + xo_emit("It was ordered on {:order\-time/%ls}.\\n", when); } .Ed @@ -766,11 +790,11 @@ will perform the conversion required to make appropriate output. Text style output uses the current locale (as described above), while XML, JSON, and HTML use -UTF-8. +UTF\-8. .Pp -UTF-8 and locale-encoded strings can use multiple bytes to encode one +UTF\-8 and locale\-encoded strings can use multiple bytes to encode one column of data. -The traditional "precision'" (aka "max-width") value +The traditional "precision" (aka "max\-width") value for "%s" printf formatting becomes overloaded since it specifies both the number of bytes that can be safely referenced and the maximum number of columns to emit. @@ -800,12 +824,12 @@ For HTML, these characters are placed in a
          with class "text". "size": "extra small" HTML:
          The hat is
          -
          extra small
          +
          extra small
          .
          .Ed -.Ss "'%n' is Not Supported" +.Ss "\(aq%n\(aq is Not Supported" .Nm libxo -does not support the '%n' directive. +does not support the \(aq%n\(aq directive. It is a bad idea and we just do not do it. .Ss "The Encoding Format (eformat)" @@ -817,7 +841,7 @@ If the primary is not given, both default to "%s". .Sh EXAMPLE In this example, the value for the number of items in stock is emitted: .Bd -literal -offset indent - xo_emit("{P: }{Lwc:In stock}{:in-stock/%u}\\n", + xo_emit("{P: }{Lwc:In stock}{:in\-stock/%u}\\n", instock); .Ed .Pp @@ -826,16 +850,16 @@ This call will generate the following output: TEXT: In stock: 144 XML: - 144 + 144 JSON: - "in-stock": 144, + "in\-stock": 144, HTML:
          In stock
          :
          -
          144
          +
          144
          .Ed .Pp @@ -846,10 +870,10 @@ or .Dv XOF_INFO data, which would expand the penultimate line to: .Bd -literal -offset indent -
          144
          +
          144
          .Ed .Sh WHAT MAKES A GOOD FIELD NAME? To make useful, consistent field names, follow these guidelines: @@ -867,23 +891,23 @@ But the raw field name should use hyphens. .Ss "Use full words" Do not abbreviate especially when the abbreviation is not obvious or not widely used. -Use "data-size", not "dsz" or "dsize". +Use "data\-size", not "dsz" or "dsize". Use -"interface" instead of "ifname", "if-name", "iface", "if", or "intf". -.Ss "Use -" -Using the form - or -- helps in +"interface" instead of "ifname", "if\-name", "iface", "if", or "intf". +.Ss "Use \-" +Using the form \- or \-\- helps in making consistent, useful names, avoiding the situation where one app -uses "sent-packet" and another "packets-sent" and another -"packets-we-have-sent". +uses "sent\-packet" and another "packets\-sent" and another +"packets\-we\-have\-sent". The can be dropped when it is obvious, as can obvious words in the classification. -Use "receive-after-window-packets" instead of -"received-packets-of-data-after-window". +Use "receive\-after\-window\-packets" instead of +"received\-packets\-of\-data\-after\-window". .Ss "Reuse existing field names" Nothing is worse than writing expressions like: .Bd -literal -offset indent if ($src1/process[pid == $pid]/name == - $src2/proc-table/proc/p[process-id == $pid]/proc-name) { + $src2/proc\-table/proc/p[process\-id == $pid]/proc\-name) { ... } .Ed @@ -903,7 +927,7 @@ calls or "{e:}" fields to make the data useful. .Ss "Do not use an arbitrary number postfix" What does "errors2" mean? No one will know. -"errors-after-restart" would be a better choice. +"errors\-after\-restart" would be a better choice. Think of your users, and think of the future. If you make "errors2", the next guy will happily make "errors3" and before you know it, someone will be asking what is the @@ -913,7 +937,7 @@ Think of your field vocabulary as an API. You want it useful, expressive, meaningful, direct, and obvious. You want the client -application's programmer to move between without the need to +application\(aqs programmer to move between without the need to understand a variety of opinions on how fields are named. They should see the system as a single cohesive whole, not a sack of cats. @@ -925,12 +949,12 @@ By choosing wise names now, you are making their lives better. After using .Xr xolint 1 to find errors in your field descriptors, use -.Dq "xolint -V" +.Dq "xolint \-V" to spell check your field names and to detect different names for the same data. -.Dq dropped-short +.Dq dropped\-short and -.Dq dropped-too-short +.Dq dropped\-too\-short are both reasonable names, but using them both will lead users to ask the difference between the two fields. If there is no difference, diff --git a/libxo/xo_parse_args.3 b/libxo/xo_parse_args.3 index 80dceca916be..487b50bafb9b 100644 --- a/libxo/xo_parse_args.3 +++ b/libxo/xo_parse_args.3 @@ -83,12 +83,16 @@ Log (via stderr) each syslog message (via Ignore the {h:} modifier (TEXT, HTML) .It Dv no-locale Do not initialize the locale setting +.It Dv no-retain +Prevent retaining formatting information .It Dv no-top Do not emit a top set of braces (JSON) .It Dv not-first Pretend the 1st output item was not 1st (JSON) .It Dv pretty Emit pretty-printed output +.It Dv retain +Force retaining formatting information .It Dv text Emit TEXT output .If Dv underscores diff --git a/packaging/libxo.pc.in b/packaging/libxo.pc.in index b291d07c9db8..0e18234f1020 100644 --- a/packaging/libxo.pc.in +++ b/packaging/libxo.pc.in @@ -5,7 +5,7 @@ includedir=@includedir@ Name: libxo -Version: @VERSION@ +Version: @LIBXO_VERSION@ Description: The XML Output Library -Libs: @LIBXO_LIBDIR@ @LIBXO_LIBS@ -Cflags: @LIBXO_INCLUDEDIR@ +Libs: -L@XO_LIBDIR@ @XO_LIBS@ +Cflags: -I@XO_INCLUDEDIR@ diff --git a/packaging/libxo.rb.base.in b/packaging/libxo.rb.base.in index 70b712da2acb..ab87be296c6c 100644 --- a/packaging/libxo.rb.base.in +++ b/packaging/libxo.rb.base.in @@ -6,15 +6,15 @@ require 'formula' class Libxo < Formula - homepage 'https://github.com/Juniper/@PACKAGE-NAME@' - url 'https://github.com/Juniper/@PACKAGE_NAME@/releases/@PACKAGE_VERSION@/@PACKAGE_NAME@-@PACKAGE_VERSION@.tar.gz' + homepage 'https://github.com/Juniper/@PACKAGE_NAME@' + url 'https://github.com/Juniper/@PACKAGE_NAME@/releases/download/@PACKAGE_VERSION@/@PACKAGE_NAME@-@PACKAGE_VERSION@.tar.gz' sha1 '__SHA1__' depends_on 'libtool' => :build def install - system "./configure", "--disable-dependency-tracking", + system "./configure", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" - system "make install" + system "make", "install" end end diff --git a/tests/core/Makefile.am b/tests/core/Makefile.am index 0131a6f50ac5..7e61f558146c 100644 --- a/tests/core/Makefile.am +++ b/tests/core/Makefile.am @@ -22,7 +22,8 @@ test_07.c \ test_08.c \ test_09.c \ test_10.c \ -test_11.c +test_11.c \ +test_12.c test_01_test_SOURCES = test_01.c test_02_test_SOURCES = test_02.c @@ -35,6 +36,7 @@ test_08_test_SOURCES = test_08.c test_09_test_SOURCES = test_09.c test_10_test_SOURCES = test_10.c test_11_test_SOURCES = test_11.c +test_12_test_SOURCES = test_12.c # TEST_CASES := $(shell cd ${srcdir} ; echo *.c ) diff --git a/tests/core/saved/test_01.E.out b/tests/core/saved/test_01.E.out index ed615a5aab84..de23baad0b16 100644 --- a/tests/core/saved/test_01.E.out +++ b/tests/core/saved/test_01.E.out @@ -2,6 +2,14 @@ op create: [] [] op open_container: [top] [] op string: [host] [my-box] op string: [domain] [example.com] +op string: [host] [my-box] +op string: [domain] [example.com] +op string: [label] [value] +op string: [max-chaos] [very] +op content: [min-chaos] [42] +op string: [some-chaos] [[42]] +op string: [host] [my-box] +op string: [domain] [example.com] op attr: [test] [value] op open_container: [data] [] op open_list: [item] [] diff --git a/tests/core/saved/test_01.H.out b/tests/core/saved/test_01.H.out index 39d8bd4e8a6f..7c0b3de061a6 100644 --- a/tests/core/saved/test_01.H.out +++ b/tests/core/saved/test_01.H.out @@ -1 +1,2 @@ -
          Connecting to
          my-box
          .
          example.com
          ...
          Item
          Total Sold
          In Stock
          On Order
          SKU
          gum
          1412
          54
          10
          GRO-000-415
          rope
          85
          4
          2
          HRD-000-212
          ladder
          0
          2
          1
          HRD-000-517
          bolt
          4123
          144
          42
          HRD-000-632
          water
          17
          14
          2
          GRO-000-2331
          Item
          '
          gum
          ':
          Total sold
          :
          1412.0
          In stock
          :
          54
          On order
          :
          10
          SKU
          :
          GRO-000-415
          Item
          '
          rope
          ':
          Total sold
          :
          85.0
          In stock
          :
          4
          On order
          :
          2
          SKU
          :
          HRD-000-212
          Item
          '
          ladder
          ':
          Total sold
          :
          0
          In stock
          :
          2
          On order
          :
          1
          SKU
          :
          HRD-000-517
          Item
          '
          bolt
          ':
          Total sold
          :
          4123.0
          In stock
          :
          144
          On order
          :
          42
          SKU
          :
          HRD-000-632
          Item
          '
          water
          ':
          Total sold
          :
          17.0
          In stock
          :
          14
          On order
          :
          2
          SKU
          :
          GRO-000-2331
          Item
          '
          fish
          ':
          Total sold
          :
          1321.0
          In stock
          :
          45
          On order
          :
          1
          SKU
          :
          GRO-000-533
          Item
          :
          gum
          Item
          :
          rope
          Item
          :
          ladder
          Item
          :
          bolt
          Item
          :
          water
          X
          X
          X
          X
          X
          X
          X
          X
          X
          X
          Cost
          :
          425
          X
          X
          Cost
          :
          455
          links
          user
          group
          /some/file
          1
          user
          group
          \ No newline at end of file +
          testing argument modifier
          my-box
          .
          example.com
          ...
          testing argument modifier with encoding to
          .
          example.com
          ...
          Label text
          value
          very
          42
          42 +
          Connecting to
          my-box
          .
          example.com
          ...
          Item
          Total Sold
          In Stock
          On Order
          SKU
          gum
          1412
          54
          10
          GRO-000-415
          rope
          85
          4
          2
          HRD-000-212
          ladder
          0
          2
          1
          HRD-000-517
          bolt
          4123
          144
          42
          HRD-000-632
          water
          17
          14
          2
          GRO-000-2331
          Item
          '
          gum
          ':
          Total sold
          :
          1412.0
          In stock
          :
          54
          On order
          :
          10
          SKU
          :
          GRO-000-415
          Item
          '
          rope
          ':
          Total sold
          :
          85.0
          In stock
          :
          4
          On order
          :
          2
          SKU
          :
          HRD-000-212
          Item
          '
          ladder
          ':
          Total sold
          :
          0
          In stock
          :
          2
          On order
          :
          1
          SKU
          :
          HRD-000-517
          Item
          '
          bolt
          ':
          Total sold
          :
          4123.0
          In stock
          :
          144
          On order
          :
          42
          SKU
          :
          HRD-000-632
          Item
          '
          water
          ':
          Total sold
          :
          17.0
          In stock
          :
          14
          On order
          :
          2
          SKU
          :
          GRO-000-2331
          Item
          '
          fish
          ':
          Total sold
          :
          1321.0
          In stock
          :
          45
          On order
          :
          1
          SKU
          :
          GRO-000-533
          Item
          :
          gum
          Item
          :
          rope
          Item
          :
          ladder
          Item
          :
          bolt
          Item
          :
          water
          X
          X
          X
          X
          X
          X
          X
          X
          X
          X
          Cost
          :
          425
          X
          X
          Cost
          :
          455
          links
          user
          group
          /some/file
          1
          user
          group
          \ No newline at end of file diff --git a/tests/core/saved/test_01.HIPx.out b/tests/core/saved/test_01.HIPx.out index a3aa369310f1..f6c7290366fb 100644 --- a/tests/core/saved/test_01.HIPx.out +++ b/tests/core/saved/test_01.HIPx.out @@ -1,4 +1,26 @@
          +
          testing argument modifier
          +
          my-box
          +
          .
          +
          example.com
          +
          ...
          +
          +
          +
          testing argument modifier with encoding to
          +
          .
          +
          example.com
          +
          ...
          +
          +
          +
          Label text
          +
          +
          value
          +
          +
          +
          very
          +
          42
          +
          42 +
          Connecting to
          my-box
          .
          diff --git a/tests/core/saved/test_01.HP.out b/tests/core/saved/test_01.HP.out index c877dfd01928..0fdcbd18005b 100644 --- a/tests/core/saved/test_01.HP.out +++ b/tests/core/saved/test_01.HP.out @@ -1,4 +1,26 @@
          +
          testing argument modifier
          +
          my-box
          +
          .
          +
          example.com
          +
          ...
          +
          +
          +
          testing argument modifier with encoding to
          +
          .
          +
          example.com
          +
          ...
          +
          +
          +
          Label text
          +
          +
          value
          +
          +
          +
          very
          +
          42
          +
          42 +
          Connecting to
          my-box
          .
          diff --git a/tests/core/saved/test_01.J.out b/tests/core/saved/test_01.J.out index 0515a2a6e615..3fc12a173148 100644 --- a/tests/core/saved/test_01.J.out +++ b/tests/core/saved/test_01.J.out @@ -1,2 +1,2 @@ -{"top": {"host":"my-box","domain":"example.com", "data": {"item": [{"sku":"GRO-000-415","name":"gum","sold":1412,"in-stock":54,"on-order":10}, {"sku":"HRD-000-212","name":"rope","sold":85,"in-stock":4,"on-order":2}, {"sku":"HRD-000-517","name":"ladder","sold":0,"in-stock":2,"on-order":1}, {"sku":"HRD-000-632","name":"bolt","sold":4123,"in-stock":144,"on-order":42}, {"sku":"GRO-000-2331","name":"water","sold":17,"in-stock":14,"on-order":2}]}, "data2": {"item": [{"sku":"GRO-000-415","name":"gum","sold":1412.0,"in-stock":54,"on-order":10}, {"sku":"HRD-000-212","name":"rope","sold":85.0,"in-stock":4,"on-order":2}, {"sku":"HRD-000-517","name":"ladder","sold":0,"in-stock":2,"on-order":1}, {"sku":"HRD-000-632","name":"bolt","sold":4123.0,"in-stock":144,"on-order":42}, {"sku":"GRO-000-2331","name":"water","sold":17.0,"in-stock":14,"on-order":2}]}, "data3": {"item": [{"sku":"GRO-000-533","name":"fish","sold":1321.0,"in-stock":45,"on-order":1}]}, "data4": {"item": ["gum","rope","ladder","bolt","water"]},"cost":425,"cost":455,"mode":"mode","mode_octal":"octal","links":"links","user":"user","group":"group","mode":"/some/file","mode_octal":640,"links":1,"user":"user","group":"group"} +{"top": {"host":"my-box","domain":"example.com","host":"my-box","domain":"example.com","label":"value","max-chaos":"very","min-chaos":42,"some-chaos":"[42]","host":"my-box","domain":"example.com", "data": {"item": [{"sku":"GRO-000-415","name":"gum","sold":1412,"in-stock":54,"on-order":10}, {"sku":"HRD-000-212","name":"rope","sold":85,"in-stock":4,"on-order":2}, {"sku":"HRD-000-517","name":"ladder","sold":0,"in-stock":2,"on-order":1}, {"sku":"HRD-000-632","name":"bolt","sold":4123,"in-stock":144,"on-order":42}, {"sku":"GRO-000-2331","name":"water","sold":17,"in-stock":14,"on-order":2}]}, "data2": {"item": [{"sku":"GRO-000-415","name":"gum","sold":1412.0,"in-stock":54,"on-order":10}, {"sku":"HRD-000-212","name":"rope","sold":85.0,"in-stock":4,"on-order":2}, {"sku":"HRD-000-517","name":"ladder","sold":0,"in-stock":2,"on-order":1}, {"sku":"HRD-000-632","name":"bolt","sold":4123.0,"in-stock":144,"on-order":42}, {"sku":"GRO-000-2331","name":"water","sold":17.0,"in-stock":14,"on-order":2}]}, "data3": {"item": [{"sku":"GRO-000-533","name":"fish","sold":1321.0,"in-stock":45,"on-order":1}]}, "data4": {"item": ["gum","rope","ladder","bolt","water"]},"cost":425,"cost":455,"mode":"mode","mode_octal":"octal","links":"links","user":"user","group":"group","mode":"/some/file","mode_octal":640,"links":1,"user":"user","group":"group"} } diff --git a/tests/core/saved/test_01.JP.out b/tests/core/saved/test_01.JP.out index 210266d87f77..2c7397f5e20a 100644 --- a/tests/core/saved/test_01.JP.out +++ b/tests/core/saved/test_01.JP.out @@ -1,5 +1,13 @@ { "top": { + "host": "my-box", + "domain": "example.com", + "host": "my-box", + "domain": "example.com", + "label": "value", + "max-chaos": "very", + "min-chaos": 42, + "some-chaos": "[42]", "host": "my-box", "domain": "example.com", "data": { diff --git a/tests/core/saved/test_01.T.out b/tests/core/saved/test_01.T.out index cdf704b880ad..71cd130ab350 100644 --- a/tests/core/saved/test_01.T.out +++ b/tests/core/saved/test_01.T.out @@ -1,3 +1,7 @@ +testing argument modifier my-box.example.com... +testing argument modifier with encoding to .example.com... +Label text value + very 4242 Connecting to my-box.example.com... Item Total Sold In Stock On Order SKU gum 1412 54 10 GRO-000-415 diff --git a/tests/core/saved/test_01.X.out b/tests/core/saved/test_01.X.out index bc9ef84f63ec..da80e681b27b 100644 --- a/tests/core/saved/test_01.X.out +++ b/tests/core/saved/test_01.X.out @@ -1 +1 @@ -my-boxexample.comGRO-000-415gum14125410HRD-000-212rope8542HRD-000-517ladder021HRD-000-632bolt412314442GRO-000-2331water17142GRO-000-415gum1412.05410HRD-000-212rope85.042HRD-000-517ladder021HRD-000-632bolt4123.014442GRO-000-2331water17.0142GRO-000-533fish1321.0451gumropeladderboltwater425455modeoctallinksusergroup/some/file6401usergroup \ No newline at end of file +my-boxexample.commy-boxexample.comvery42[42]my-boxexample.comGRO-000-415gum14125410HRD-000-212rope8542HRD-000-517ladder021HRD-000-632bolt412314442GRO-000-2331water17142GRO-000-415gum1412.05410HRD-000-212rope85.042HRD-000-517ladder021HRD-000-632bolt4123.014442GRO-000-2331water17.0142GRO-000-533fish1321.0451gumropeladderboltwater425455modeoctallinksusergroup/some/file6401usergroup \ No newline at end of file diff --git a/tests/core/saved/test_01.XP.out b/tests/core/saved/test_01.XP.out index f7d7e5c9246f..c331dceafe62 100644 --- a/tests/core/saved/test_01.XP.out +++ b/tests/core/saved/test_01.XP.out @@ -1,4 +1,12 @@ + my-box + example.com + my-box + example.com + + very + 42 + [42] my-box example.com diff --git a/tests/core/saved/test_12.E.err b/tests/core/saved/test_12.E.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.E.out b/tests/core/saved/test_12.E.out new file mode 100644 index 000000000000..1c899a165664 --- /dev/null +++ b/tests/core/saved/test_12.E.out @@ -0,0 +1,89 @@ +op create: [] [] +op open_container: [top] [] +op open_container: [data] [] +op open_list: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op open_instance: [thing] [] +op string: [name] [thing] +op string: [color] [green] +op content: [time] [2:15] +op string: [hand] [left] +op string: [color] [blue] +op content: [time] [3:45] +op close_instance: [thing] [] +op close_list: [thing] [] +op close_container: [data] [] +op close_container: [top] [] +op finish: [] [] +op flush: [] [] diff --git a/tests/core/saved/test_12.H.err b/tests/core/saved/test_12.H.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.H.out b/tests/core/saved/test_12.H.out new file mode 100644 index 000000000000..5cbac1797776 --- /dev/null +++ b/tests/core/saved/test_12.H.out @@ -0,0 +1 @@ +
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          The
          thing
          is
          green
          til
          02:15
          My
          left
          hand is
          blue
          til
          03:45
          \ No newline at end of file diff --git a/tests/core/saved/test_12.HIPx.err b/tests/core/saved/test_12.HIPx.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.HIPx.out b/tests/core/saved/test_12.HIPx.out new file mode 100644 index 000000000000..9b5fea1ca4af --- /dev/null +++ b/tests/core/saved/test_12.HIPx.out @@ -0,0 +1,160 @@ +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          diff --git a/tests/core/saved/test_12.HP.err b/tests/core/saved/test_12.HP.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.HP.out b/tests/core/saved/test_12.HP.out new file mode 100644 index 000000000000..1e0e9233fbe5 --- /dev/null +++ b/tests/core/saved/test_12.HP.out @@ -0,0 +1,160 @@ +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          +
          +
          The
          +
          thing
          +
          is
          +
          green
          +
          til
          +
          02:15
          +
          +
          +
          My
          +
          left
          +
          hand is
          +
          blue
          +
          til
          +
          03:45
          +
          diff --git a/tests/core/saved/test_12.J.err b/tests/core/saved/test_12.J.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.J.out b/tests/core/saved/test_12.J.out new file mode 100644 index 000000000000..118bb760eefb --- /dev/null +++ b/tests/core/saved/test_12.J.out @@ -0,0 +1,2 @@ +{"top": {"data": {"thing": [{"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}, {"name":"thing","color":"green","time":2:15,"hand":"left","color":"blue","time":3:45}]}} +} diff --git a/tests/core/saved/test_12.JP.err b/tests/core/saved/test_12.JP.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.JP.out b/tests/core/saved/test_12.JP.out new file mode 100644 index 000000000000..3e15e0d554cc --- /dev/null +++ b/tests/core/saved/test_12.JP.out @@ -0,0 +1,88 @@ +{ + "top": { + "data": { + "thing": [ + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + }, + { + "name": "thing", + "color": "green", + "time": 2:15, + "hand": "left", + "color": "blue", + "time": 3:45 + } + ] + } + } +} diff --git a/tests/core/saved/test_12.T.err b/tests/core/saved/test_12.T.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.T.out b/tests/core/saved/test_12.T.out new file mode 100644 index 000000000000..6f777c7a1f44 --- /dev/null +++ b/tests/core/saved/test_12.T.out @@ -0,0 +1,20 @@ +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 +The thing is green til 02:15 +My left hand is blue til 03:45 diff --git a/tests/core/saved/test_12.X.err b/tests/core/saved/test_12.X.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.X.out b/tests/core/saved/test_12.X.out new file mode 100644 index 000000000000..ed2d8e44e07a --- /dev/null +++ b/tests/core/saved/test_12.X.out @@ -0,0 +1 @@ +thinggreenleftbluethinggreenleftbluethinggreenleftbluethinggreenleftbluethinggreenleftbluethinggreenleftbluethinggreenleftbluethinggreenleftbluethinggreenleftbluethinggreenleftblue \ No newline at end of file diff --git a/tests/core/saved/test_12.XP.err b/tests/core/saved/test_12.XP.err new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/tests/core/saved/test_12.XP.out b/tests/core/saved/test_12.XP.out new file mode 100644 index 000000000000..73eec4c675b6 --- /dev/null +++ b/tests/core/saved/test_12.XP.out @@ -0,0 +1,84 @@ + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + thing + green + + left + blue + + + + diff --git a/tests/core/test_01.c b/tests/core/test_01.c index 5c748772fb9f..05d778a0bca4 100644 --- a/tests/core/test_01.c +++ b/tests/core/test_01.c @@ -79,6 +79,18 @@ main (int argc, char **argv) xo_open_container_h(NULL, "top"); + xo_emit("testing argument modifier {a:}.{a:}...\n", + "host", "my-box", "domain", "example.com"); + + xo_emit("testing argument modifier with encoding to {ea:}.{a:}...\n", + "host", "my-box", "domain", "example.com"); + + xo_emit("{La:} {a:}\n", "Label text", "label", "value"); + + xo_emit_field("Vt", "max-chaos", NULL, NULL, " very "); + xo_emit_field("V", "min-chaos", "%d", NULL, 42); + xo_emit_field("V", "some-chaos", "%d\n", "[%d]", 42); + xo_emit("Connecting to {:host}.{:domain}...\n", "my-box", "example.com"); xo_attr("test", "value"); diff --git a/tests/core/test_02.c b/tests/core/test_02.c index abddcf273c97..9a0268009915 100644 --- a/tests/core/test_02.c +++ b/tests/core/test_02.c @@ -42,6 +42,7 @@ main (int argc, char **argv) } xo_set_flags(NULL, XOF_UNITS); /* Always test w/ this */ + xo_set_file(stdout); xo_open_container_h(NULL, "top"); diff --git a/tests/core/test_12.c b/tests/core/test_12.c new file mode 100644 index 000000000000..17d26a6dae54 --- /dev/null +++ b/tests/core/test_12.c @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2014, Juniper Networks, Inc. + * All rights reserved. + * This SOFTWARE is licensed under the LICENSE provided in the + * ../Copyright file. By downloading, installing, copying, or otherwise + * using the SOFTWARE, you agree to be bound by the terms of that + * LICENSE. + * Phil Shafer, July 2014 + */ + +#include +#include +#include +#include + +#include "xo_config.h" +#include "xo.h" + +int +main (int argc, char **argv) +{ + int i, count = 10; + int mon = 0; + xo_emit_flags_t flags = XOEF_RETAIN; + + argc = xo_parse_args(argc, argv); + if (argc < 0) + return 1; + + for (argc = 1; argv[argc]; argc++) { + if (strcmp(argv[argc], "xml") == 0) + xo_set_style(NULL, XO_STYLE_XML); + else if (strcmp(argv[argc], "json") == 0) + xo_set_style(NULL, XO_STYLE_JSON); + else if (strcmp(argv[argc], "text") == 0) + xo_set_style(NULL, XO_STYLE_TEXT); + else if (strcmp(argv[argc], "html") == 0) + xo_set_style(NULL, XO_STYLE_HTML); + else if (strcmp(argv[argc], "pretty") == 0) + xo_set_flags(NULL, XOF_PRETTY); + else if (strcmp(argv[argc], "xpath") == 0) + xo_set_flags(NULL, XOF_XPATH); + else if (strcmp(argv[argc], "info") == 0) + xo_set_flags(NULL, XOF_INFO); + else if (strcmp(argv[argc], "no-retain") == 0) + flags &= ~XOEF_RETAIN; + else if (strcmp(argv[argc], "big") == 0) { + if (argv[argc + 1]) + count = atoi(argv[++argc]); + } + } + + xo_set_flags(NULL, XOF_UNITS); /* Always test w/ this */ + xo_set_file(stdout); + + xo_open_container("top"); + xo_open_container("data"); + + const char *fmt1 = "The {C:fg-red}{k:name}{C:reset} is " + "{C:/fg-%s}{:color}{C:reset} til {:time/%02d:%02d}\n"; + const char *fmt2 = "My {C:fg-red}{:hand}{C:reset} hand is " + "{C:/fg-%s}{:color}{C:reset} til {:time/%02d:%02d}\n"; + + for (i = 0; i < count; i++) { + xo_open_instance("thing"); + xo_emit_f(flags, fmt1, "thing", "green", "green", 2, 15); + xo_emit_f(flags, fmt2, "left", "blue", "blue", 3, 45); + } + + xo_close_container("data"); + xo_close_container_h(NULL, "top"); + + xo_finish(); + + return 0; +} diff --git a/tests/gettext/gt_01.c b/tests/gettext/gt_01.c index a0200c2926c4..d63674745d6d 100644 --- a/tests/gettext/gt_01.c +++ b/tests/gettext/gt_01.c @@ -26,7 +26,7 @@ int main (int argc, char **argv) { static char domainname[] = "gt_01"; - char path[MAXPATHLEN]; + static char path[MAXPATHLEN]; const char *tzone = "EST"; const char *lang = "pig_latin"; From 83f290755088ae7a0168cc4e41cf746d09684cf6 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Fri, 15 Apr 2016 18:32:05 +0000 Subject: [PATCH 135/143] Set CPP from XCPP for the libcompat build. Submitted by: Mark Millard --- Makefile.libcompat | 1 + 1 file changed, 1 insertion(+) diff --git a/Makefile.libcompat b/Makefile.libcompat index 560a50c42573..2cbaf2e0f196 100644 --- a/Makefile.libcompat +++ b/Makefile.libcompat @@ -94,6 +94,7 @@ LIBCOMPATWMAKEENV+= BUILD_TOOLS_META=.NOMETA_CMP .endif LIBCOMPATWMAKEFLAGS+= CC="${XCC} ${LIBCOMPATCFLAGS}" \ CXX="${XCXX} ${LIBCOMPATCFLAGS} ${LIBCOMPATCXXFLAGS}" \ + CPP="${XCPP} ${LIBCOMPATCFLAGS}" \ DESTDIR=${LIBCOMPATTMP} \ -DNO_CPU_CFLAGS \ MK_CTF=no \ From 21e2745698dd9e509a4e6b2095eab27e5e3a2661 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Fri, 15 Apr 2016 18:43:54 +0000 Subject: [PATCH 136/143] Add SHLIB_CXX to allow building a C++ shared library without a static one. Submitted by: ngie Sponsored by: EMC / Isilon Storage Division --- share/mk/bsd.lib.mk | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/share/mk/bsd.lib.mk b/share/mk/bsd.lib.mk index 4e22e92e6a7b..eb1417900313 100644 --- a/share/mk/bsd.lib.mk +++ b/share/mk/bsd.lib.mk @@ -4,12 +4,17 @@ .include -.if defined(LIB_CXX) -LIB= ${LIB_CXX} +.if defined(LIB_CXX) || defined(SHLIB_CXX) _LD= ${CXX} .else _LD= ${CC} .endif +.if defined(LIB_CXX) +LIB= ${LIB_CXX} +.endif +.if defined(SHLIB_CXX) +SHLIB= ${SHLIB_CXX} +.endif LIB_PRIVATE= ${PRIVATELIB:Dprivate} # Set up the variables controlling shared libraries. After this section, From 86abeac495df122f22ea3f644e9dc5f7fd400cbc Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Fri, 15 Apr 2016 18:49:26 +0000 Subject: [PATCH 137/143] Document SHLIB/SHLIB_CXX/NO_PIC. Sponsored by: EMC / Isilon Storage Division --- share/mk/bsd.README | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/share/mk/bsd.README b/share/mk/bsd.README index b0719593f6d8..e38695592821 100644 --- a/share/mk/bsd.README +++ b/share/mk/bsd.README @@ -419,12 +419,16 @@ with the current needs of the BSD tree. It sets/uses the following variables: -LIB The name of the library to build. +LIB The name of the library to build. Both a shared and static + library will be built. NO_PIC can be set to only build a + static library. LIB_CXX The name of the library to build. It also causes to link the library with the standard C++ library. LIB_CXX overrides the value - of LIB if LIB is also set. + of LIB if LIB is also set. Both a shared and static library + will be built. NO_PIC can be set to only build a static + library. LIBDIR Target directory for libraries. @@ -449,6 +453,10 @@ SRCS List of source files to build the library. Suffix types to .c files of the same name. (This is not the default for versions of make.) +SHLIB Like LIB but only builds a shared library. + +SHLIB_CXX Like LIB_CXX but only builds a shared library. + SHLIB_LDSCRIPT Template file to generate shared library linker script. Unless used, a simple symlink is created to the real shared object. From d938d64e553345deeba0735ba3226dc90586c011 Mon Sep 17 00:00:00 2001 From: Ed Maste Date: Fri, 15 Apr 2016 19:06:36 +0000 Subject: [PATCH 138/143] elfcopy: fix symbol table handling when sections come after symtab/strtab Fix a symbol table handling bug in elfcopy: elfcopy puts .symtab, .strtab and .shstrtab sections in the end of the output object. If the input objects have more sections after any of these 3 sections, the section table will be reordered, and in that case the section symbols should be regenerated for relocations. The bug is triggered since newer clang puts .strtab section in the beginning of the object produced. Ticket: #525 Reported by: royger Obtained from: ELF Tool Chain r3443 --- contrib/elftoolchain/elfcopy/sections.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/contrib/elftoolchain/elfcopy/sections.c b/contrib/elftoolchain/elfcopy/sections.c index 5848eab7d3f7..143413847851 100644 --- a/contrib/elftoolchain/elfcopy/sections.c +++ b/contrib/elftoolchain/elfcopy/sections.c @@ -343,7 +343,7 @@ create_scn(struct elfcopy *ecp) GElf_Shdr ish; size_t indx; uint64_t oldndx, newndx; - int elferr, sec_flags; + int elferr, sec_flags, reorder; /* * Insert a pseudo section that contains the ELF header @@ -367,6 +367,7 @@ create_scn(struct elfcopy *ecp) errx(EXIT_FAILURE, "elf_getshstrndx failed: %s", elf_errmsg(-1)); + reorder = 0; is = NULL; while ((is = elf_nextscn(ecp->ein, is)) != NULL) { if (gelf_getshdr(is, &ish) == NULL) @@ -482,8 +483,20 @@ create_scn(struct elfcopy *ecp) /* create section header based on input object. */ if (strcmp(name, ".symtab") != 0 && strcmp(name, ".strtab") != 0 && - strcmp(name, ".shstrtab") != 0) + strcmp(name, ".shstrtab") != 0) { copy_shdr(ecp, s, NULL, 0, sec_flags); + /* + * elfcopy puts .symtab, .strtab and .shstrtab + * sections in the end of the output object. + * If the input objects have more sections + * after any of these 3 sections, the section + * table will be reordered. section symbols + * should be regenerated for relocations. + */ + if (reorder) + ecp->flags &= ~SYMTAB_INTACT; + } else + reorder = 1; if (strcmp(name, ".symtab") == 0) { ecp->flags |= SYMTAB_EXIST; From fca840765590388382625617720269fe5346709f Mon Sep 17 00:00:00 2001 From: Conrad Meyer Date: Fri, 15 Apr 2016 20:19:32 +0000 Subject: [PATCH 139/143] savecore(8): Explicitly cast to fix i386 warning --- sbin/savecore/savecore.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sbin/savecore/savecore.c b/sbin/savecore/savecore.c index 63f4ef26e5db..1d00ed24aa5b 100644 --- a/sbin/savecore/savecore.c +++ b/sbin/savecore/savecore.c @@ -506,7 +506,7 @@ DoFile(const char *savedir, const char *device) } } if (lseek(fd, lasthd, SEEK_SET) != lasthd || - read(fd, temp, sectorsize) != sectorsize) { + read(fd, temp, sectorsize) != (ssize_t)sectorsize) { syslog(LOG_ERR, "error reading last dump header at offset %lld in %s: %m", (long long)lasthd, device); @@ -584,7 +584,7 @@ DoFile(const char *savedir, const char *device) dumpsize = dtoh64(kdhl.dumplength); firsthd = lasthd - dumpsize - sectorsize; if (lseek(fd, firsthd, SEEK_SET) != firsthd || - read(fd, temp, sectorsize) != sectorsize) { + read(fd, temp, sectorsize) != (ssize_t)sectorsize) { syslog(LOG_ERR, "error reading first dump header at offset %lld in %s: %m", (long long)firsthd, device); @@ -743,7 +743,7 @@ DoFile(const char *savedir, const char *device) memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof(kdhl.magic)); memcpy(temp, &kdhl, sizeof(kdhl)); if (lseek(fd, lasthd, SEEK_SET) != lasthd || - write(fd, temp, sectorsize) != sectorsize) + write(fd, temp, sectorsize) != (ssize_t)sectorsize) syslog(LOG_ERR, "error while clearing the dump header: %m"); } From 2dbc59317660f194d1b3ef0a72e1cdb273ec30b9 Mon Sep 17 00:00:00 2001 From: Hiren Panchasara Date: Fri, 15 Apr 2016 20:27:36 +0000 Subject: [PATCH 140/143] Fix the 'type' for a few variables from tcpcb. Reviewed by: markj Sponsored by: Limelight Networks Differential Revision: https://reviews.freebsd.org/D5973 --- cddl/lib/libdtrace/tcp.d | 8 ++++---- share/man/man4/dtrace_tcp.4 | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cddl/lib/libdtrace/tcp.d b/cddl/lib/libdtrace/tcp.d index ec7350336d5a..9b27076d8096 100644 --- a/cddl/lib/libdtrace/tcp.d +++ b/cddl/lib/libdtrace/tcp.d @@ -108,16 +108,16 @@ typedef struct tcpsinfo { uint32_t tcps_snxt; /* next sequence # to send */ uint32_t tcps_rack; /* sequence # we have acked */ uint32_t tcps_rnxt; /* next sequence # expected */ - uint32_t tcps_swnd; /* send window size */ + u_long tcps_swnd; /* send window size */ int32_t tcps_snd_ws; /* send window scaling */ uint32_t tcps_swl1; /* window update seg seq number */ uint32_t tcps_swl2; /* window update seg ack number */ uint32_t tcps_rup; /* receive urgent pointer */ uint32_t tcps_radv; /* advertised window */ - uint32_t tcps_rwnd; /* receive window size */ + u_long tcps_rwnd; /* receive window size */ int32_t tcps_rcv_ws; /* receive window scaling */ - uint32_t tcps_cwnd; /* congestion window */ - uint32_t tcps_cwnd_ssthresh; /* threshold for congestion avoidance */ + u_long tcps_cwnd; /* congestion window */ + u_long tcps_cwnd_ssthresh; /* threshold for congestion avoidance */ uint32_t tcps_srecover; /* for use in NewReno Fast Recovery */ uint32_t tcps_sack_fack; /* SACK sequence # we have acked */ uint32_t tcps_sack_snxt; /* next SACK seq # for retransmission */ diff --git a/share/man/man4/dtrace_tcp.4 b/share/man/man4/dtrace_tcp.4 index d7ab30ce55f6..d230066106d4 100644 --- a/share/man/man4/dtrace_tcp.4 +++ b/share/man/man4/dtrace_tcp.4 @@ -24,7 +24,7 @@ .\" .\" $FreeBSD$ .\" -.Dd July 5, 2015 +.Dd April 15, 2016 .Dt DTRACE_TCP 4 .Os .Sh NAME @@ -217,17 +217,17 @@ Next sequence number for send. Sequence number of received and acknowledged data. .It Vt uint32_t tcps_rnxt Next expected sequence number for receive. -.It Vt uint32_t tcps_swnd +.It Vt u_long tcps_swnd TCP send window size. .It Vt int32_t tcps_snd_ws Window scaling factor for the TCP send window. -.It Vt uint32_t tcps_rwnd +.It Vt u_long tcps_rwnd TCP receive window size. .It Vt int32_t tcps_rcv_ws Window scaling factor for the TCP receive window. -.It Vt uint32_t tcps_cwnd +.It Vt u_long tcps_cwnd TCP congestion window size. -.It Vt uint32_t tcps_cwnd_ssthresh +.It Vt u_long tcps_cwnd_ssthresh Congestion window threshold at which slow start ends and congestion avoidance begins. .It Vt uint32_t tcps_sack_fack From 14a0ca29fe703fdb1903fd229ad762a1192690c7 Mon Sep 17 00:00:00 2001 From: Luiz Otavio O Souza Date: Fri, 15 Apr 2016 21:31:40 +0000 Subject: [PATCH 141/143] Replace with . No functional change. Sponsored by: Rubicon Communications (Netgate) --- sys/conf/NOTES | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sys/conf/NOTES b/sys/conf/NOTES index ec5618c5af04..406373f9f8ea 100644 --- a/sys/conf/NOTES +++ b/sys/conf/NOTES @@ -719,7 +719,7 @@ options ALTQ_CBQ # Class Based Queueing options ALTQ_RED # Random Early Detection options ALTQ_RIO # RED In/Out options ALTQ_HFSC # Hierarchical Packet Scheduler -options ALTQ_FAIRQ # Fair Packet Scheduler +options ALTQ_FAIRQ # Fair Packet Scheduler options ALTQ_CDNR # Traffic conditioner options ALTQ_PRIQ # Priority Queueing options ALTQ_NOPCC # Required if the TSC is unusable From 80c7cc1c8f027fcf5d5f0a2df4b9aef6904ed079 Mon Sep 17 00:00:00 2001 From: "Pedro F. Giffuni" Date: Fri, 15 Apr 2016 22:31:22 +0000 Subject: [PATCH 142/143] Cleanup unnecessary semicolons from utilities we all love. --- sbin/dump/optr.c | 2 +- sbin/fsck_ffs/globs.c | 2 +- sbin/ifconfig/sfp.c | 2 +- sbin/mount_nfs/mount_nfs.c | 2 +- usr.bin/bsdiff/bsdiff/bsdiff.c | 50 +++++++++++++-------------- usr.bin/bsdiff/bspatch/bspatch.c | 4 +-- usr.bin/calendar/dates.c | 2 +- usr.bin/calendar/io.c | 2 +- usr.bin/rpcgen/rpc_cout.c | 2 +- usr.bin/rpcgen/rpc_main.c | 2 +- usr.bin/rpcgen/rpc_parse.c | 2 +- usr.bin/rpcgen/rpc_svcout.c | 2 +- usr.bin/rpcgen/rpc_util.c | 4 +-- usr.bin/showmount/showmount.c | 6 ++-- usr.bin/sort/bwstring.c | 2 +- usr.bin/sort/coll.c | 2 +- usr.bin/sort/file.c | 2 +- usr.bin/truss/syscalls.c | 2 +- usr.bin/xlint/lint1/func.c | 2 +- usr.bin/xstr/xstr.c | 2 +- usr.sbin/keyserv/keyserv.c | 2 +- usr.sbin/lmcconfig/lmcconfig.c | 2 +- usr.sbin/mountd/mountd.c | 6 ++-- usr.sbin/nfscbd/nfscbd.c | 2 +- usr.sbin/nfsd/nfsd.c | 2 +- usr.sbin/pmcstudy/pmcstudy.c | 2 +- usr.sbin/portsnap/phttpget/phttpget.c | 2 +- usr.sbin/ppp/radius.c | 2 +- 28 files changed, 58 insertions(+), 58 deletions(-) diff --git a/sbin/dump/optr.c b/sbin/dump/optr.c index 311e2551affc..bffcdc8bb7e8 100644 --- a/sbin/dump/optr.c +++ b/sbin/dump/optr.c @@ -403,7 +403,7 @@ lastdump(int arg) /* w ==> just what to do; W ==> most recent dumps */ dumpme = tnow > (dtwalk->dd_ddate - (tlast->tm_hour * 3600) - (tlast->tm_min * 60) - tlast->tm_sec + (dt->fs_freq * 86400)); - }; + } if (arg != 'w' || dumpme) (void) printf( "%c %8s\t(%6s) Last dump: Level %d, Date %s\n", diff --git a/sbin/fsck_ffs/globs.c b/sbin/fsck_ffs/globs.c index e910bc9f4e83..af3b72bd7e57 100644 --- a/sbin/fsck_ffs/globs.c +++ b/sbin/fsck_ffs/globs.c @@ -118,7 +118,7 @@ fsckinit(void) bzero(totalreadcnt, sizeof(long) * BT_NUMBUFTYPES); bzero(readtime, sizeof(struct timespec) * BT_NUMBUFTYPES); bzero(totalreadtime, sizeof(struct timespec) * BT_NUMBUFTYPES); - bzero(&startprog, sizeof(struct timespec));; + bzero(&startprog, sizeof(struct timespec)); bzero(&sblk, sizeof(struct bufarea)); pdirbp = NULL; pbp = NULL; diff --git a/sbin/ifconfig/sfp.c b/sbin/ifconfig/sfp.c index d92ee2cb2a32..0fa29a3d150d 100644 --- a/sbin/ifconfig/sfp.c +++ b/sbin/ifconfig/sfp.c @@ -911,6 +911,6 @@ sfp_status(int s, struct ifreq *ifr, int verbose) break; default: print_sfp_status(&ii, verbose); - }; + } } diff --git a/sbin/mount_nfs/mount_nfs.c b/sbin/mount_nfs/mount_nfs.c index 810cf59da0c4..149d127a11d9 100644 --- a/sbin/mount_nfs/mount_nfs.c +++ b/sbin/mount_nfs/mount_nfs.c @@ -1027,7 +1027,7 @@ xdr_fh(XDR *xdrsp, struct nfhret *np) if (!authfnd && (authcnt > 0 || np->auth != AUTH_SYS)) np->stat = EAUTH; return (1); - }; + } return (0); } diff --git a/usr.bin/bsdiff/bsdiff/bsdiff.c b/usr.bin/bsdiff/bsdiff/bsdiff.c index 7e39275a0a46..e0b3ee7d2553 100644 --- a/usr.bin/bsdiff/bsdiff/bsdiff.c +++ b/usr.bin/bsdiff/bsdiff/bsdiff.c @@ -57,24 +57,24 @@ static void split(off_t *I,off_t *V,off_t start,off_t len,off_t h) if(V[I[k+i]+h]start) split(I,V,start,jj-start,h); @@ -137,10 +137,10 @@ static void qsufsort(off_t *I,off_t *V,u_char *old,off_t oldsize) split(I,V,i,len,h); i+=len; len=0; - }; - }; + } + } if(len) I[i-len]=-len; - }; + } for(i=0;iSf*2-lenf) { Sf=s; lenf=i; }; - }; + if(s*2-i>Sf*2-lenf) { Sf=s; lenf=i; } + } lenb=0; if(scan=lastscan+i)&&(pos>=i);i++) { if(old[pos-i]==new[scan-i]) s++; - if(s*2-i>Sb*2-lenb) { Sb=s; lenb=i; }; - }; - }; + if(s*2-i>Sb*2-lenb) { Sb=s; lenb=i; } + } + } if(lastscan+lenf>scan-lenb) { overlap=(lastscan+lenf)-(scan-lenb); @@ -348,12 +348,12 @@ int main(int argc,char *argv[]) old[lastpos+lenf-overlap+i]) s++; if(new[scan-lenb+i]== old[pos-lenb+i]) s--; - if(s>Ss) { Ss=s; lens=i+1; }; - }; + if(s>Ss) { Ss=s; lens=i+1; } + } lenf+=lens-overlap; lenb-=lens; - }; + } for(i=0;inewsize) @@ -195,7 +195,7 @@ int main(int argc,char * argv[]) /* Adjust pointers */ newpos+=ctrl[1]; oldpos+=ctrl[2]; - }; + } /* Clean up the bzip2 reads */ BZ2_bzReadClose(&cbz2err, cpfbz2); diff --git a/usr.bin/calendar/dates.c b/usr.bin/calendar/dates.c index a5f5e9fa0286..86d8a1fee9ff 100644 --- a/usr.bin/calendar/dates.c +++ b/usr.bin/calendar/dates.c @@ -381,7 +381,7 @@ walkthrough_dates(struct event **e) d = m->days; *e = d->events; return (1); - }; + } if (d->nextday != NULL) { d = d->nextday; *e = d->events; diff --git a/usr.bin/calendar/io.c b/usr.bin/calendar/io.c index 89863f45d7f0..0a5dd854546f 100644 --- a/usr.bin/calendar/io.c +++ b/usr.bin/calendar/io.c @@ -469,7 +469,7 @@ closecal(FILE *fp) if (setuid(getuid()) < 0) { warnx("setuid failed"); _exit(1); - }; + } if (setgid(getegid()) < 0) { warnx("setgid failed"); _exit(1); diff --git a/usr.bin/rpcgen/rpc_cout.c b/usr.bin/rpcgen/rpc_cout.c index 4c36ce6c583d..0c2ce2098b36 100644 --- a/usr.bin/rpcgen/rpc_cout.c +++ b/usr.bin/rpcgen/rpc_cout.c @@ -81,7 +81,7 @@ emit(definition *def) if (strcmp(def->def.ty.old_type, def->def_name) == 0) return; - }; + } print_header(def); switch (def->def_kind) { case DEF_UNION: diff --git a/usr.bin/rpcgen/rpc_main.c b/usr.bin/rpcgen/rpc_main.c index b7b255afa586..64a29adc94f2 100644 --- a/usr.bin/rpcgen/rpc_main.c +++ b/usr.bin/rpcgen/rpc_main.c @@ -977,7 +977,7 @@ checkfiles(const char *infile, const char *outfile) { warn("%s", infile); crash(); - }; + } if (outfile) { if (stat(outfile, &buf) < 0) return; /* file does not exist */ diff --git a/usr.bin/rpcgen/rpc_parse.c b/usr.bin/rpcgen/rpc_parse.c index f7f857a0c9a5..69392b702a35 100644 --- a/usr.bin/rpcgen/rpc_parse.c +++ b/usr.bin/rpcgen/rpc_parse.c @@ -329,7 +329,7 @@ def_union(definition *defp) *tailp = cases; tailp = &cases->next; cases = XALLOC(case_list); - }; + } get_declaration(&dec, DEF_UNION); cases->case_decl = dec; diff --git a/usr.bin/rpcgen/rpc_svcout.c b/usr.bin/rpcgen/rpc_svcout.c index 4b951a337df4..aa5a86ad2ba9 100644 --- a/usr.bin/rpcgen/rpc_svcout.c +++ b/usr.bin/rpcgen/rpc_svcout.c @@ -551,7 +551,7 @@ write_program(definition *def, const char *storage) (void) sprintf(_errbuf, "unable to free results"); print_err_message("\t\t"); f_print(fout, "\n"); - }; + } print_return("\t"); f_print(fout, "}\n"); } diff --git a/usr.bin/rpcgen/rpc_util.c b/usr.bin/rpcgen/rpc_util.c index bf0ca5dee91f..14741186d5d7 100644 --- a/usr.bin/rpcgen/rpc_util.c +++ b/usr.bin/rpcgen/rpc_util.c @@ -454,7 +454,7 @@ add_type(int len, const char *type) { typ_list_t->next = ptr; typ_list_t = ptr; - }; + } } @@ -470,7 +470,7 @@ find_type(const char *type) return (ptr); else ptr = ptr->next; - }; + } return (NULL); } diff --git a/usr.bin/showmount/showmount.c b/usr.bin/showmount/showmount.c index 46e58e4ba74a..01c9e261c753 100644 --- a/usr.bin/showmount/showmount.c +++ b/usr.bin/showmount/showmount.c @@ -194,7 +194,7 @@ main(int argc, char **argv) default: printf("Hosts on %s:\n", host); break; - }; + } print_dump(mntdump); } if (rpcs & DOEXPORTS) { @@ -317,7 +317,7 @@ xdr_mntdump(XDR *xdrsp, struct mountlist **mlp) goto next; } break; - }; + } if (val < 0) { otp = &tp->ml_left; tp = tp->ml_left; @@ -407,7 +407,7 @@ print_dump(struct mountlist *mp) default: printf("%s\n", mp->ml_host); break; - }; + } if (mp->ml_right) print_dump(mp->ml_right); } diff --git a/usr.bin/sort/bwstring.c b/usr.bin/sort/bwstring.c index fc30b56ae885..3965eaed1c98 100644 --- a/usr.bin/sort/bwstring.c +++ b/usr.bin/sort/bwstring.c @@ -297,7 +297,7 @@ bwscsbdup(const unsigned char *str, size_t len) /* NOTREACHED */ err(2, "mbrtowc error"); cptr += charlen; - }; + } } ret->len = chars; diff --git a/usr.bin/sort/coll.c b/usr.bin/sort/coll.c index 0b7eb571b8f5..7b4ad1067810 100644 --- a/usr.bin/sort/coll.c +++ b/usr.bin/sort/coll.c @@ -688,7 +688,7 @@ static void setsuffix(wchar_t c, unsigned char *si) break; default: *si = 0; - }; + } } /* diff --git a/usr.bin/sort/file.c b/usr.bin/sort/file.c index 0a0088947dee..47d59af5b1dd 100644 --- a/usr.bin/sort/file.c +++ b/usr.bin/sort/file.c @@ -1258,7 +1258,7 @@ sort_list_to_file(struct sort_list *list, const char *outfile) break; default: errx(2, "%s", getstr(10)); - }; + } } if (sort_opts_vals.sort_method == SORT_DEFAULT) diff --git a/usr.bin/truss/syscalls.c b/usr.bin/truss/syscalls.c index 9f291f051927..3bf7b9d69ede 100644 --- a/usr.bin/truss/syscalls.c +++ b/usr.bin/truss/syscalls.c @@ -1197,7 +1197,7 @@ print_arg(struct syscall_args *sc, unsigned long *args, long *retval, break; len--; truncated = 1; - }; + } fprintf(fp, "\"%s\"%s", tmp3, truncated ? "..." : ""); free(tmp3); diff --git a/usr.bin/xlint/lint1/func.c b/usr.bin/xlint/lint1/func.c index 893121e56d8d..e5a0490c5a3a 100644 --- a/usr.bin/xlint/lint1/func.c +++ b/usr.bin/xlint/lint1/func.c @@ -517,7 +517,7 @@ label(int typ, sym_t *sym, tnode_t *tn) ci->c_default = 1; } break; - }; + } reached = 1; } diff --git a/usr.bin/xstr/xstr.c b/usr.bin/xstr/xstr.c index 670e09ebafc7..4aad8e66e74a 100644 --- a/usr.bin/xstr/xstr.c +++ b/usr.bin/xstr/xstr.c @@ -139,7 +139,7 @@ main(int argc, char *argv[]) argc--, argv++; else readstd = 0; - }; + } flushsh(); if (cflg == 0) xsdotc(); diff --git a/usr.sbin/keyserv/keyserv.c b/usr.sbin/keyserv/keyserv.c index 79bf90d0f1df..8acbaf699d9c 100644 --- a/usr.sbin/keyserv/keyserv.c +++ b/usr.sbin/keyserv/keyserv.c @@ -440,7 +440,7 @@ key_net_put_2_svc_prog(uid, arg) arg->st_netname, (int)sizeof (arg->st_pub_key), arg->st_pub_key, (int)sizeof (arg->st_priv_key), arg->st_priv_key); - }; + } status = pk_netput(uid, arg); diff --git a/usr.sbin/lmcconfig/lmcconfig.c b/usr.sbin/lmcconfig/lmcconfig.c index f720e634f8ff..eb80dbe31495 100644 --- a/usr.sbin/lmcconfig/lmcconfig.c +++ b/usr.sbin/lmcconfig/lmcconfig.c @@ -1528,7 +1528,7 @@ print_test_pattern(int patt) case 11: printf("framed X^23+X^18+1\n"); break; - case 12:; + case 12: printf("framed X^11+X^9+1 w/7ZS\n"); break; case 13: diff --git a/usr.sbin/mountd/mountd.c b/usr.sbin/mountd/mountd.c index d6da2bc9c24c..a9464f68fe48 100644 --- a/usr.sbin/mountd/mountd.c +++ b/usr.sbin/mountd/mountd.c @@ -434,7 +434,7 @@ main(int argc, char **argv) break; default: usage(); - }; + } if (modfind("nfsd") < 0) { /* Not present in kernel, try loading it */ @@ -1241,7 +1241,7 @@ xdr_fhs(XDR *xdrsp, caddr_t cp) return (0); return (xdr_long(xdrsp, &auth)); } - }; + } return (0); } @@ -2540,7 +2540,7 @@ do_mount(struct exportlist *ep, struct grouplist *grp, int exflags, *cp = savedc; ret = 1; goto error_exit; - }; + } /* * For V4:, use the nfssvc() syscall, instead of mount(). diff --git a/usr.sbin/nfscbd/nfscbd.c b/usr.sbin/nfscbd/nfscbd.c index c9153b432f1e..4bcfd6ea95da 100644 --- a/usr.sbin/nfscbd/nfscbd.c +++ b/usr.sbin/nfscbd/nfscbd.c @@ -177,7 +177,7 @@ main(int argc, char *argv[]) default: case '?': usage(); - }; + } argv += optind; argc -= optind; diff --git a/usr.sbin/nfsd/nfsd.c b/usr.sbin/nfsd/nfsd.c index f58ed30023ae..349ba8e60929 100644 --- a/usr.sbin/nfsd/nfsd.c +++ b/usr.sbin/nfsd/nfsd.c @@ -214,7 +214,7 @@ main(int argc, char **argv) default: case '?': usage(); - }; + } if (!tcpflag && !udpflag) udpflag = 1; argv += optind; diff --git a/usr.sbin/pmcstudy/pmcstudy.c b/usr.sbin/pmcstudy/pmcstudy.c index 16c9f5148334..e94addfb5700 100644 --- a/usr.sbin/pmcstudy/pmcstudy.c +++ b/usr.sbin/pmcstudy/pmcstudy.c @@ -2873,7 +2873,7 @@ main(int argc, char **argv) printf("-A -- Run all canned tests\n"); return(0); break; - }; + } } if ((run_all == 0) && (name == NULL) && (filename == NULL) && (test_mode == 0) && (master_exp == NULL)) { diff --git a/usr.sbin/portsnap/phttpget/phttpget.c b/usr.sbin/portsnap/phttpget/phttpget.c index 1bf6d9d5b153..33e969a63ed3 100644 --- a/usr.sbin/portsnap/phttpget/phttpget.c +++ b/usr.sbin/portsnap/phttpget/phttpget.c @@ -598,7 +598,7 @@ main(int argc, char *argv[]) fd = open(fname, O_CREAT | O_TRUNC | O_WRONLY, 0644); if (fd == -1) errx(1, "open(%s)", fname); - }; + } /* Read the message and send data to fd if appropriate */ if (chunked) { diff --git a/usr.sbin/ppp/radius.c b/usr.sbin/ppp/radius.c index f79814125eef..12b0c0f9a6e7 100644 --- a/usr.sbin/ppp/radius.c +++ b/usr.sbin/ppp/radius.c @@ -1150,7 +1150,7 @@ radius_Account(struct radius *r, struct radacct *ac, struct datalink *dl, snprintf(ac->multi_session_id, sizeof ac->multi_session_id, "%s", dl->bundle->ncp.mp.active ? dl->bundle->ncp.mp.server.socket.sun_path : ""); - }; + } if (rad_put_string(r->cx.rad, RAD_USER_NAME, ac->user_name) != 0 || rad_put_int(r->cx.rad, RAD_SERVICE_TYPE, RAD_FRAMED) != 0 || From d1ad1a7394330d70efc2f2c58862a02dd8900acf Mon Sep 17 00:00:00 2001 From: John Baldwin Date: Sat, 16 Apr 2016 00:01:16 +0000 Subject: [PATCH 143/143] Add a test for cancelling an active AIO request on a socket. The older AIO code awakened all pending AIO requests on a socket when any data arrived. This could result in AIO daemons blocking on an empty socket buffer. These requests could not be cancelled which led to a deadlock during process exit. This test reproduces this case. The newer AIO code is able to cancel the pending AIO request correctly. Reviewed by: ngie (-ish) Sponsored by: Chelsio Communications Differential Revision: https://reviews.freebsd.org/D4363 --- tests/sys/aio/aio_test.c | 60 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/tests/sys/aio/aio_test.c b/tests/sys/aio/aio_test.c index 5515161ee489..1b1008829352 100644 --- a/tests/sys/aio/aio_test.c +++ b/tests/sys/aio/aio_test.c @@ -722,6 +722,65 @@ ATF_TC_BODY(aio_large_read_test, tc) close(fd); } +/* + * This tests for a bug where arriving socket data can wakeup multiple + * AIO read requests resulting in an uncancellable request. + */ +ATF_TC_WITHOUT_HEAD(aio_socket_two_reads); +ATF_TC_BODY(aio_socket_two_reads, tc) +{ + struct ioreq { + struct aiocb iocb; + char buffer[1024]; + } ioreq[2]; + struct aiocb *iocb; + unsigned i; + int s[2]; + char c; + + ATF_REQUIRE_KERNEL_MODULE("aio"); +#if __FreeBSD_version < 1100101 + aft_tc_skip("kernel version %d is too old (%d required)", + __FreeBSD_version, 1100101); +#endif + + ATF_REQUIRE(socketpair(PF_UNIX, SOCK_STREAM, 0, s) != -1); + + /* Queue two read requests. */ + memset(&ioreq, 0, sizeof(ioreq)); + for (i = 0; i < nitems(ioreq); i++) { + ioreq[i].iocb.aio_nbytes = sizeof(ioreq[i].buffer); + ioreq[i].iocb.aio_fildes = s[0]; + ioreq[i].iocb.aio_buf = ioreq[i].buffer; + ATF_REQUIRE(aio_read(&ioreq[i].iocb) == 0); + } + + /* Send a single byte. This should complete one request. */ + c = 0xc3; + ATF_REQUIRE(write(s[1], &c, sizeof(c)) == 1); + + ATF_REQUIRE(aio_waitcomplete(&iocb, NULL) == 1); + + /* Determine which request completed and verify the data was read. */ + if (iocb == &ioreq[0].iocb) + i = 0; + else + i = 1; + ATF_REQUIRE(ioreq[i].buffer[0] == c); + + i ^= 1; + + /* + * Try to cancel the other request. On broken systems this + * will fail and the process will hang on exit. + */ + ATF_REQUIRE(aio_error(&ioreq[i].iocb) == EINPROGRESS); + ATF_REQUIRE(aio_cancel(s[0], &ioreq[i].iocb) == AIO_CANCELED); + + close(s[1]); + close(s[0]); +} + ATF_TP_ADD_TCS(tp) { @@ -732,6 +791,7 @@ ATF_TP_ADD_TCS(tp) ATF_TP_ADD_TC(tp, aio_pipe_test); ATF_TP_ADD_TC(tp, aio_md_test); ATF_TP_ADD_TC(tp, aio_large_read_test); + ATF_TP_ADD_TC(tp, aio_socket_two_reads); return (atf_no_error()); }